gpt4 book ai didi

java - 使用 Gson 将 JSON 转换为 Java 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:38:28 25 4
gpt4 key购买 nike

我正在尝试将 JSON 字符串转换为简单的 Java 对象,但它返回 null。以下是类(class)详情。

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

}

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

最佳答案

您的 JSON 是一个包含字段 menu 的对象。

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

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", } } 有一个错误,它有一个额外的逗号。应该是:

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

关于java - 使用 Gson 将 JSON 转换为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6897068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com