【问题标题】:how to convert json data to java object and how to separate json data fields如何将json数据转换为java对象以及如何分隔json数据字段
【发布时间】:2018-05-29 12:36:27
【问题描述】:

我正在使用来自 url 的数据并存储在“输出”字符串中。
如何将其转换为 java 对象和单独的字段?
这是我的代码:

Client client = Client.create();
WebResource webResource = client
  .resource(url);
String name = "xxx";
String password = "xxx";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString
  .getBytes());
//System.out.println("Base64 encoded auth string: " + authStringEnc);
ClientResponse response = webResource.accept("application/json")
  .header("Authorization", "Basic " + authStringEnc)
  .get(ClientResponse.class);
String output = response.getEntity(String.class);


System.out.println("Output from Server .... \n");
System.out.println(output);

【问题讨论】:

标签: java json rest


【解决方案1】:

您可以为此使用gson 。将 gson 导入您的项目。

    import java.lang.reflect.Type;
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;

    //..
    //you can get the output here
    //String output = response.getEntity(String.class);

    Type listType = new TypeToken<FooObject>(){}.getType();
    FooObject fooObject =new Gson().fromJson(output, listType);

【讨论】:

  • 类型 listType = new TypeToken(){}.getType();学生 student =new Gson().fromJson(output, listType); System.out.println(学生); o/p :Student [college_name=null,college_id=0] 它的显示是这样的。我想获得特定的列(college_name)值。你能告诉我解决方案吗
  • 是的,没错。请检查此example,您可以将类型修改为对象或集合。
  • 我希望该 json 对象存储到数据库中。我如何将该 json 数据发送到数据库。我得到这样的 o/p:({"counts":[{"college_name":"kit", hyd","college_id":777}........ .............我在db中创建了表。我想将这些json数据存储到该表中。
  • 我正在从客户端获取数据。所以我想直接将该数据添加到 db 表中。如何将 thjat json 数据转换为 java 对象以及如何保存到表的特定列中。
  • 好的。我知道你想做什么。你能发布 output 的 json 数据吗?你只需要修改你的对象来捕获 json 数据
猜你喜欢
  • 2010-12-13
  • 2011-03-17
  • 2011-05-20
  • 2011-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多