使用 Gson 将 JSON 转换为 Java 对象

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

Converting JSON to Java object using Gson

javaandroidjsongson

提问by Avnish

I am trying to convert JSON string to simple java object but it is returning null. Below are the class details.

我正在尝试将 JSON 字符串转换为简单的 java 对象,但它返回 null。以下是班级详情。

JSON String:

JSON 字符串:

   {"menu": 
    {"id": "file",
     "value": "File",
     }
   }

This is parsable class:

这是可解析的类:

public static void main(String[] args) {
try {
    Reader r = new
         InputStreamReader(TestGson.class.getResourceAsStream("testdata.json"), "UTF-8");
    String s = Helper.readAll(r);
    Gson gson = new Gson();
    Menu m = gson.fromJson(s, Menu.class);
    System.out.println(m.getId());
    System.out.println(m.getValue());
    } catch (IOException e) {
    e.printStackTrace();
    }
}

Below are th model class:

以下是模型类:

public class Menu {

    String id;
    String value;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }

    public String toString() {
        return String.format("id: %s, value: %d", id, value);
    }

}

Everytime i am getting null. Can anyone please help me?

每次我都为空。谁能帮帮我吗?

回答by Jonas

Your JSON is an object with a field menu.

您的 JSON 是一个带有字段的对象menu

If you add the same in your Java it works:

如果您在 Java 中添加相同的内容,它会起作用:

class MenuWrapper {
    Menu menu;
    public Menu getMenu() { return menu; }
    public void setMenu(Menu m) { menu = m; }
}

And an example:

和一个例子:

public static void main(String[] args) {
    String json =  "{\"menu\": {\"id\": \"file\", \"value\": \"File\"} }";

    Gson gson = new Gson();
    MenuWrapper m = gson.fromJson(json, MenuWrapper.class);
    System.out.println(m.getMenu().getId());
    System.out.println(m.getMenu().getValue());

}

It will print:

它会打印:

file
File

And your JSON: {"menu": {"id": "file", "value": "File", } }has an error, it has an extra comma. It should be:

而你的 JSON:{"menu": {"id": "file", "value": "File", } }有一个错误,它有一个额外的逗号。它应该是:

{"menu": {"id": "file", "value": "File" } }

回答by Miserable Variable

What I have found helpful with Gson is to create an an instance of the class, call toJson()on it and compare the generated string with the string I am trying to parse.

我发现对 Gson 有帮助的是创建一个类的实例,调用toJson()它并将生成的字符串与我试图解析的字符串进行比较。