json存取对象 java_java – 如何读取json文件,并使用GSON将其转换为POJO

我需要将值从json文件传递到java类,json文件就像这样的例子:

{

"id":1,

"name":"Gold",

"description":"Shiny!",

"spriteId":1,

"consumable":true,

"effectsId":[1]

},

我需要映射,我做了这个:

Items i = new Items();

Map mapaNomes = new HashMap();

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

}

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 mapaNomeses = new Gson().fromJson(

reader,

new TypeToken>() {}.getType());

Then you can do whatever you want with each and every one of them

for (MapaNomes mapaNomes : mapaNomeses) {

// whatever

}

标签:json,java,android,gson

来源: https://codeday.me/bug/20190609/1202748.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值