使用GSON解析JSON文件 [英] Parse JSON file using GSON

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

问题描述

我想使用 GSON JAVA 中解析 JSON 文件:

描述符{
app1:{
name:mehdi,
age:21 ,
messages:[msg 1,msg 2,msg 3]
},
app2:{
name:mkyong ,
age:29,
messages:[msg 11,msg 22,msg 33]
},
app3: {
name:amine,
age:23,
messages:[msg 111,msg 222,msg 333]
}
}
}

但我不知道如何加入到描述符,然后是 app3 元素,最后是名称元素。



我遵循本教程方法。

例如:

  class Response {
Map< String,应用>描述;
//标准getters& setters ...
}

class App {
String name;
int age;
String []消息;
//标准getters& setters ...
}

然后使用:

  Gson gson = new Gson(); 
响应响应= gson.fromJson(yourJson,Response.class);

其中 yourJson 可以是 字符串 ,任何< a href =https://docs.oracle.com/javase/7/docs/api/java/io/Reader.html> Reader JsonReader JsonElement

最后,如果你想访问任何特定的字段,你只需要做:

  String name = response.getDescriptor()。get(app3)。getName(); 

您可以按照其他答案中的建议手动解析JSON,但是我个人认为这种方法更清晰,从长远来看更具可维护性,并且更适合JSON的整体构想。

I want to parse this JSON file in JAVA using GSON :

{
    "descriptor" : {
        "app1" : {
            "name" : "mehdi",
            "age" : 21,
            "messages": ["msg 1","msg 2","msg 3"]
        },
        "app2" : {
            "name" : "mkyong",
            "age" : 29,
            "messages": ["msg 11","msg 22","msg 33"]
        },
        "app3" : {
            "name" : "amine",
            "age" : 23,
            "messages": ["msg 111","msg 222","msg 333"]
        }
    }
}

but I don't know how to acceed to the root element which is : descriptor, after that the app3 element and finally the name element.

I followed this tutorial http://www.mkyong.com/java/gson-streaming-to-read-and-write-json/, but it doesn't show the case of having a root and childs elements.

解决方案

Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then use Gson.fromJson() method.
For example:

class Response {
    Map<String, App> descriptor;
    // standard getters & setters...
}

class App {
  String name;
  int age;
  String[] messages;
  // standard getters & setters...
}

Then just use:

Gson gson = new Gson();
Response response = gson.fromJson(yourJson, Response.class);

Where yourJson can be a String, any Reader, a JsonReader or a JsonElement.

Finally, if you want to access any particular field, you just have to do:

String name = response.getDescriptor().get("app3").getName();

You can always parse the JSON manually as suggested in other answers, but personally I think this approach is clearer, more maintainable in long term and it fits better with the whole idea of JSON.

这篇关于使用GSON解析JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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