【问题标题】:How to convert JSON to Object format in Java?如何在 Java 中将 JSON 转换为 Object 格式?
【发布时间】:2019-12-13 23:40:27
【问题描述】:

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

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; 
    }

这是我尝试过的,但它没有返回任何值。

我必须以对象格式获取 JOSN 值,然后必须插入 MySQL DB。

【问题讨论】:

  • 如果可能,请添加您的User 课程。另外,是否打印了任何错误消息?
  • 你用过jackson注解吗,请贴出用户类?

标签: java spring-boot


【解决方案1】:

您拥有的链接的响应不是User,而是List&lt;User&gt; - 尝试反序列化。

您的代码应该与此类似(我试图美化一下):

    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();
    }

正如 cmets 中所述,这对演员表有警告。

【讨论】:

  • 这会起作用,但传递 List.class 会从编译器发出警告,因为您传递的是非参数化列表。
  • @ThomasAndolf 是的。看到他的代码,他似乎不会介意:)
【解决方案2】:

Jackson 是一个 JSON 序列化器/反序列化器,默认包含在 spring 中,RestTemplate 默认使用。

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

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&lt;User&gt; 包装成ParameterizedTypeReference 来绕过这个问题,ParameterizedTypeReference 是用于此的类型,用于向类型添加参数(列表是一种类型,它需要一个参数,在这种情况下是用户)。

您可以在此处阅读更多信息Sending lists with RestTemplate

【讨论】:

    【解决方案3】:

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

    首先,您需要三个库“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 将包含所有来过的用户。

    【讨论】:

      【解决方案4】:

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

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

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

          你可以试试这个在Java中将JSON转换为对象

          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);
             }
          

          【讨论】:

            【解决方案7】:

            您必须从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);
                }
            }
            

            【讨论】:

              猜你喜欢
              • 2019-03-18
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-07-25
              • 1970-01-01
              • 1970-01-01
              • 2011-04-07
              相关资源
              最近更新 更多