`

使用Gson 解析json文件

    博客分类:
  • java
阅读更多

近期工作中使用json文件做了配置文件

test.json

{

"product_01":[{"name1":"computer"},{"price1":"4198.00"},{"makeDate":"2014-07-17"}],

"product_02":[{"name2":"phone"},{"price2":"1198.00"},{"makeDate":"2014-09-21"}]

}

 

使用Gson解析上面的json文件的java代码

public class GsonTest_02 {

 

//gson测试

@Test

public void test_01() {

try {

String filePath = "./configs/test.json";

InputStream is = new FileInputStream(new File(filePath));

Reader reader = new InputStreamReader(is);

GsonBuilder builder = new GsonBuilder();

Gson gson = builder.create();

Map<String, Object> maps = gson.fromJson(reader, new TypeToken<Map<String, Object>>(){}.getType());

for (Map.Entry<String, Object> map : maps.entrySet()) {

//System.out.println(map.getKey() + ":" + map.getValue());

List<Object> childMap = (ArrayList<Object>) map.getValue();

for (Object object : childMap) {

Map<String, Object> jsons = (Map<String, Object>) object;

for(Map.Entry<String, Object> json : jsons.entrySet() ) {

System.out.println(json.getKey() + ":" + json.getValue());

}

}

}

 

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

 

}

 

测试结果:

name1:computer

price1:4198.00

makeDate:2014-07-17

name2:phone

price2:1198.00

makeDate:2014-09-21

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics