Java 如何将 JSON 字符串转换为自定义对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20194124/
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-13 00:10:52  来源:igfitidea点击:

How to convert JSON string to custom object?

javajson

提问by sensorario

I've string like this (just )

我有这样的字符串(只是)

"{\"username":\"stack\",\"over":\"flow\"}"

I'd successfully converted this string to JSON with

我已经成功地将此字符串转换为 JSON

JSONObject object = new JSONObject("{\"username":\"stack\",\"over":\"flow\"}");

I've a class

我有一堂课

public class MyClass
{
    public String username;
    public String over;
}

How can I convert JSONObject into my custom MyClass object?

如何将 JSONObject 转换为我的自定义 MyClass 对象?

采纳答案by Konstantin Yovkov

You can implement a static method in MyClassthat takes JSONObjectas a parameter and returns a MyClassinstance. For example:

您可以实现一个静态方法MyClass,将其JSONObject作为参数并返回一个MyClass实例。例如:

public static MyClass convertFromJSONToMyClass(JSONObject json) {
    if (json == null) {
        return null;
    }
    MyClass result = new MyClass();
    result.username = (String) json.get("username");
    result.name = (String) json.get("name");
    return result;
}

回答by Goran ?tuc

you need Gson:

你需要 Gson:

Gson gson = new Gson(); 
final MyClass myClass = gson.fromJson(jsonString, MyClass.class);

also what might come handy in future projects for you: Json2Pojo Class generator

还有什么可能在未来的项目中对你有用: Json2Pojo 类生成器