如何将json数据转换为java对象以及如何分离json数据字段

时间:2017-12-15 10:08:18

标签: java json rest

我正在使用来自url的数据并存储在“output”字符串中。
如何将其转换为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);

1 个答案:

答案 0 :(得分:0)

您可以使用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);