我需要将值从 json 文件传递到 java 类,json 文件就像这个例子:
{
"id":1,
"name":"Gold",
"description":"Shiny!",
"spriteId":1,
"consumable":true,
"effectsId":[1]
},
我需要映射,我这样做了:
Items i = new Items();
Map<String, Items> mapaNomes = new HashMap<String, Items>();
mapaNomes.put("Gold",i);
mapaNomes.put("Apple",i );
mapaNomes.put("Clain Mail",i );
我是 android 开发的新手,我可能忘记了一些东西,因为以下内容不起作用,有人可以帮助找出问题所在吗?
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Gson gson = new Gson();
Items Items = gson.fromJson((BufferedReader) mapaNomes, Items.class);
最佳答案
1。为您的 Json 创建您的 POJO 表示。
public class MapaNomes() {
String name;
String description;
// etc
public String getName() {
return name;
}
// create your other getters and setters
}
我发现这个工具可以方便地将 json 转换为 POJO。 http://www.jsonschema2pojo.org/
2。阅读你的 file.json。把它变成对象
JsonReader reader = new JsonReader(new FileReader("file.json"));
MapaNomes mapaNomes = new Gson().fromJson(reader, MapaNomes.class);
奖金
我认为您的 file.json 中可能有许多 json 对象,例如:
{
"id":1,
"name":"Gold",
"description":"Shiny!",
"spriteId":1,
"consumable":true,
"effectsId":[1]
},
...
{
"id":999,
"name":"Silver",
"description":"Whatever!",
"spriteId":808,
"consumable":true,
"effectsId":[2]
},
如果是这种情况,那么您可以执行以下操作:
JsonReader reader = new JsonReader(new FileReader("file.json"));
List<MapaNomes> mapaNomeses = new Gson().fromJson(
reader,
new TypeToken<List<Review>>() {}.getType());
Then you can do whatever you want with each and every one of them
for (MapaNomes mapaNomes : mapaNomeses) {
// whatever
}
关于java - 如何读取 json 文件,并使用 GSON 将其转换为 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33293403/