简体   繁体   English

使用Gson将JSON转换为Java对象

[英]Converting JSON to Java object using Gson

I am trying to convert JSON string to simple java object but it is returning null. 我试图将JSON字符串转换为简单的java对象,但它返回null。 Below are the class details. 以下是课程详情。

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? 谁能帮帮我吗?

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. 而你的JSON: {"menu": {"id": "file", "value": "File", } }有一个错误,它有一个额外的逗号。 It should be: 它应该是:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM