如何在Java中将JSON转换为对象格式?

时间:2019-08-06 12:04:59

标签: java spring-boot

我有一个链接https://jsonplaceholder.typicode.com/posts,它以JSON格式返回数据。如何将其转换为对象格式?

public String ExposeServices() {
        RestTemplate restTemplate= new RestTemplate();
        String forresouseURL="https://jsonplaceholder.typicode.com/posts";
        ResponseEntity<String> response= restTemplate.getForEntity(forresouseURL, String.class);
        Gson gson = new Gson(); // Or use new GsonBuilder().create();
        String target2 = gson.toJson(response, User.class);
        HashMap<String, String> jsonObject= response;
        System.out.println(target2);
        //response.getBody().
        return target2; 
    }

这是我尝试过的方法,但未返回任何值。

我必须获取Object格式的JOSN值,然后才能在MySQL DB中插入

7 个答案:

答案 0 :(得分:2)

您所拥有的链接的响应不是User,而是List<User>-请尝试对此进行反序列化。

您的代码应与此类似(我尝试对此进行美化):

    public List<User> exposeServices() {
        RestTemplate restTemplate= new RestTemplate();
        ResponseEntity<String> response= restTemplate.getForEntity("https://jsonplaceholder.typicode.com/posts", String.class);
        Gson gson = new Gson();
        return gson.fromJson(response.getBody(), List.class);
    }

另外,如果您没有特定的理由使用Gson,我想您可以这样做:

    public List<User> exposeServices() {
        RestTemplate restTemplate= new RestTemplate();
        return restTemplate.getForEntity("https://jsonplaceholder.typicode.com/posts", List.class).getBody();
    }

如评论中所述,这在演员表上有警告。

答案 1 :(得分:0)

Jackson是JSON序列化器/反序列化器,默认情况下包含在spring中,默认情况下由RestTemplate使用。

端点返回的是用户列表,因此您不能直接将其反序列化为User,它必须是类型List<User>

public List<User> exposeServices() {
    RestTemplate restTemplate= new RestTemplate();
    return restTemplate.exchange("https://jsonplaceholder.typicode.com/posts", 
        HttpMethod.GET, 
        null,   
        new ParameterizedTypeReference<List<User>>() {})
        .getBody();
}

如果仅将List.class传递给RestTemplate,它将不知道要包含的列表是什么,并且可能会从编译器得到警告。

我们可以通过将List<User>包装到ParameterizedTypeReference中来绕过这一点,- name: copying server.crt and ca.crt become: true copy: src={{ item.src }} dest={{ item.dest }} with_items: - { src: '/tmp/server.crt' , dest: '/etc/openvpn/server.crt' } - { src: '/tmp/ca.crt' , dest: '/etc/openvpn/ca.crt' } remote_src: true 是为此使用的类型,用于向类型中添加参数(在这种情况下,list是一个类型,并且它需要一个参数用户)。

您可以在这里Sending lists with RestTemplate

了解更多信息

答案 2 :(得分:-1)

这是重复的问题:Google Gson - deserialize list<class> object? (generic type)

您的解决方案使用数组而不是一个对象:

User[] users = gson.fromJson(response, User[].class);

答案 3 :(得分:-1)

使用Jackson的FasterXML库。它们有一个ObjectMapper类,只要您告诉它哪些字段是哪个字段,就可以让您从JSON转换为Java对象。

答案 4 :(得分:-1)

您可以为此使用以下解决方案

首先,您需要三个库“ Jackson-Databind”,“ jackson-annotations”和“ jackson-core”,它们应该具有相同的版本。以下是示例代码

String jsonString = "<The json user list you received>";
     ObjectMapper mapper = new ObjectMapper();

    List user =  mapper.readValue(jsonString.getBytes(), List.class);

    Iterator it = user.iterator();

    List<User> userList = new ArrayList<>();

    while(it.hasNext())
    {
        User receivedUser = new User();
        LinkedHashMap receivedMap = (LinkedHashMap)it.next();
        receivedUser.setUserId((Integer)receivedMap.get("userId"));
        receivedUser.setId((Integer)receivedMap.get("id"));
        receivedUser.setTitle((String)receivedMap.get("title"));
        receivedUser.setBody((String)receivedMap.get("body"));
        userList.add(receivedUser);
    }

我已经创建了用户类。最后,userList将包含所有来访的用户。

答案 5 :(得分:-2)

您可以尝试将JSON转换为Java中的对象

public class JSONToJavaExample
{
   public static void main(String[] args)
   {
      Student S1= null;
      ObjectMapper mapper = new ObjectMapper();
      try
      {
         S1 =  mapper.readValue(new File("json file path"), Student.class);
      } catch (JsonGenerationException e)
      {
         e.printStackTrace();
      } catch (JsonMappingException e)
      {
         e.printStackTrace();
      } catch (IOException e)
      {
     e.printStackTrace();
      }
      System.out.println(S1);
   }

答案 6 :(得分:-2)

您将必须从此link

下载json依赖项
import org.json.JSONArray;
import org.json.JSONObject;

public class ParseJSON {

    static String json = "{/Your json string/}";

    public static void main(String[] args) {
        JSONObject obj = new JSONObject(json);
    }
}