19

在 Java 中(使用 json-simple),我成功地解析了一个使用 JSON.stringify 在 JavaScript 中创建的 JSON 字符串。它看起来像这样:

{"teq":14567,"ver":1,"rev":1234,"cop":15678}

这个字符串存储了一个自定义 JavaScript 对象的状态,我现在希望将其重组为纯 Java 类。它进展不顺利 - 第一次涉足 Java 来自 C# 背景。:-p

该对象当前采用 org.json.simple.JSONObject 的形式,因为这是 json-simple 从 JSONParser.parse() 操作生成的。

如何将此 JSONObject 转换为我的新 Java 类?(其定义如下……)

public class MyCustomJSObject {
    public int teq;
    public int ver;
    public int rev;
    public int cop;
}
4

5 回答 5

21

从https://github.com/google/gson添加依赖项并像使用它一样使用它

Gson gson= new Gson();
CustomPOJOClass obj = gson.fromJson(jsonObject.toString(),CustomPOJOClass.class);
于 2017-01-19T06:35:20.957 回答
19

使用杰克逊库

    //create ObjectMapper instance
    ObjectMapper objectMapper = new ObjectMapper();

    //convert json string to object
    Employee emp = objectMapper.readValue(jsonData, Employee.class); 
于 2014-06-15T15:42:25.253 回答
7

有很多图书馆可以做到这一点。这是我的建议。在这里你可以找到图书馆

import com.google.gson.Gson; 

然后做,

Gson gson = new Gson();  
Student student = gson.fromJson(jsonStringGoesHere, Student.class);  

Maven 依赖

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.4</version>
    </dependency>
于 2014-06-15T15:44:20.853 回答
4

2018 年 1 月 9 日更新

自从提出这个(现在很流行)问题以来已经过去了几年。虽然我仍然同意 json-simple 是我当时的需要,但经过反思,我认为在杰克逊解决方案旁边加上“复选标记”可以更好地服务于 SO 社区。我今天不接受我自己的回答;杰克逊真的很棒!


我认为这个体面的 json-simple 库是糟糕文档的受害者。如果你不使用 JSONParser (看图!),而是使用这个 JSONValue.parse() 方法,一切都会像这样:

    //JSONParser parser = new JSONParser(); // DON'T USE THIS
    Object obj = JSONValue.parse("A JSON string - array of objects: [{},{}] - goes here");
    JSONArray arrFilings = (JSONArray)obj;
    System.out.println("We can print one this way...");
    System.out.println(arrFilings.get(5) + "\n");

    System.out.println("We can enumerate the whole array...");
    for(Object objFiling : arrFilings){
        System.out.println(objFiling);
    }
    System.out.println("\n");

    System.out.println("We can access object properties this way...");
    for(Object objFiling : arrFilings){
        JSONObject o = (JSONObject)objFiling; // MUST cast to access .get()
        MyJSObject.fyq = o.get("fyq");
    }
    System.out.println("\n");

感谢所有发帖的人。坚持使用 json-simple 是问题所在,这是迄今为止唯一的 json-simple 答案。杰克逊看起来很漂亮,亚马逊也在他们的 Java 开发工具包中使用它,所以……如果它对 AWS 来说足够好的话……

于 2014-06-16T04:32:23.153 回答
2

JSON 字符串到 Java 类?你可以试试fastjson:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.1.41</version>
</dependency>

并使用java代码:

MyCustomJSObject object = JSON.parseObject(jsonString,MyCustomJSObject.class); 
于 2014-06-15T15:41:33.913 回答