如何将 JSONObject 转换为自定义 Java 类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24231223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:59:03  来源:igfitidea点击:

How can I cast a JSONObject to a custom Java class?

javajson-simple

提问by Geek Stocks

In Java (using json-simple) I have successfully parsed a JSON string which was created in JavaScript using JSON.stringify. It looks like this:

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

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

This string is storing the state of a custom JavaScript object which I now wish to re-constitute as a pure Java class. Its not going well - first foray into Java coming from a C# background. :-p

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

The object is currently in the form of a org.json.simple.JSONObject since that is what json-simple made from the JSONParser.parse() operation.

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

How can I cast this JSONObject to my new Java class?(the definition of which is below...)

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

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

采纳答案by arsen_adzhiametov

use Hymanson library

使用Hyman逊库

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

    //convert json string to object
    Employee emp = objectMapper.readValue(jsonData, Employee.class); 

回答by Vito

JSON string to Java Class ? you can trying fastjson:

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

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

and using java code:

并使用java代码:

MyCustomJSObject object = JSON.parseObject(jsonString,MyCustomJSObject.class); 

回答by diyoda_

There are lot of libraries that does this. This is my suggestion. Hereyou can find the library

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

import com.google.gson.Gson; 

and then do,

然后做,

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

Maven Dependency

Maven 依赖

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.4</version>
    </dependency>

回答by Geek Stocks

UPDATE 1/9/2018

更新 1/9/2018

Some years have passed since this (now popular) question was asked. While I still agree that json-simple was my need at the time, upon reflection I think the SO community is better served by having the "checkmark" next to the Hymanson solution. I am un-accepting my own answer today; Hymanson is pretty great!

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



I think that this decent json-simple library is the victim of poor documentation. If you don't use the JSONParser (go figure!) but instead use this JSONValue.parse() method, it all works out like 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");

Thanks to all those who posted. Sticking with json-simple was the question and this is the only json-simple answer to-date. Hymanson DOES look slick, and Amazon uses it in their SDK for Java too, sooo.... if its good enough for AWS....

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

回答by Milon

Add dependency from https://github.com/google/gsonand use it like

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

Gson gson= new Gson();
CustomPOJOClass obj = gson.fromJson(jsonObject.toString(),CustomPOJOClass.class);