使用Gson将JSON转换为Java对象 [英] Converting JSON to Java object using Gson

查看:111
本文介绍了使用Gson将JSON转换为Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

JSON字符串:

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

这是可解析的类:

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();
    }
}

以下是模型类:

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?

推荐答案

你的JSON是一个带字段菜单的对象

Your JSON is an object with a field menu.

如果你在Java中添加相同的东西:

If you add the same in your Java it works:

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

例如:

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());

}

将打印:

file
File

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

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

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

这篇关于使用Gson将JSON转换为Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆