在Android中使用GSON解析复杂的JSON对象

发布于 2024-10-09 07:27:42 字数 499 浏览 2 评论 0 原文

我对 Java 编程比较陌生,需要通过网络解析复杂的 JSON 对象。过去一天我一直在阅读有关 GSON 的文档,但没能完全解析这种类型的结构:

{
  'Events' : [{
    'name' : 'exp',
    'date' : '10-10-2010',
    'tags' : ["tag 1", "tag2", "tag3"]
    },...more events...],
  'Contacts' : [{
    'name' : 'John Smith',
    'date' : '10-10-2010',
    'tags' : ["tag 1", "tag2", "tag3"]
    },...more contacts...],
}

我已经能够让它以类似于 这个问题,但无法弄清楚如何让额外的数组级别发挥作用。

I'm relatively new to Java programming and need to parse a complex JSON object across the wire. I've been reading documentation on GSON the past day and Haven't had much luck being able to fully parse this type of structure:

{
  'Events' : [{
    'name' : 'exp',
    'date' : '10-10-2010',
    'tags' : ["tag 1", "tag2", "tag3"]
    },...more events...],
  'Contacts' : [{
    'name' : 'John Smith',
    'date' : '10-10-2010',
    'tags' : ["tag 1", "tag2", "tag3"]
    },...more contacts...],
}

I've been able to get it to work similarly to this question but can't figure out how to get that additional array level to work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

埖埖迣鎅 2024-10-16 07:27:42

使用我正在寻找的格式的 GSON 执行此操作的正确方法是:

//somewhere after the web response:
Gson gson = new Gson();

Event[] events = gson.fromJson(webServiceResponse,  Event[].class);


//somewhere nested in the class:
static class Event{
    String name;
    String date;

    public String getName()
    {
        return name;
    }

    public String getDate()
    {
        return date;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setDate(String date)
    {
        this.date = date;
    }
}

The correct way to do it using GSON in the format I'm looking for is:

//somewhere after the web response:
Gson gson = new Gson();

Event[] events = gson.fromJson(webServiceResponse,  Event[].class);


//somewhere nested in the class:
static class Event{
    String name;
    String date;

    public String getName()
    {
        return name;
    }

    public String getDate()
    {
        return date;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setDate(String date)
    {
        this.date = date;
    }
}
俏︾媚 2024-10-16 07:27:42

Java 有他自己的 JSON 解析器:我们也可以在 Android 上使用它。

您可以在下面找到如何从字符串中获取所有事件。

String TAG        = "JSON EXAMPLE";
    String jsonString = "{\"Events\" : [{\"name\" : \"exp\",\"date\" : \"10-10-2010\",\"tags\" : [\"tag 1\",\"tag 2\",\"tag 3\"]}],\"Contacts\" : [{\"name\" : \"John Smith\",\"date\" : \"10-10-2010\",\"tags\" : [\"tag 1\",\"tag 2\",\"tag 3\"]}]}";

    try {
        JSONObject jsonObj    = new JSONObject(jsonString);     // create a json object from a string
        JSONArray  jsonEvents = jsonObj.getJSONArray("Events"); // get all events as json objects from Events array

        for(int i = 0; i < jsonEvents.length(); i++){
            JSONObject event = jsonEvents.getJSONObject(i); // create a single event jsonObject
            Log.e(TAG, "Event name:" + event.getString("name") + " date: " + event.getString("date"));


            JSONArray eventTags = event.getJSONArray("tags");

            for(int j = 0; j < eventTags.length(); j++){
                Log.e(TAG, "Event tag: " + eventTags.getString(j));
            }

        }           

    } catch (JSONException e) {
        e.printStackTrace();
    }

请注意:您的 JSON 对象(来自您的问题)将抛出异常,因为它无效(我不确定,但它看起来像一个 javascript 对象)。您必须向每个属性(键)添加一些引号,并用 \ (\") 转义它们。
这个 工具 非常适合测试 JSON 字符串是否有效。

Java has his own JSON parser: we can use it on Android as well.

Below you can find how you can get all events from your String.

String TAG        = "JSON EXAMPLE";
    String jsonString = "{\"Events\" : [{\"name\" : \"exp\",\"date\" : \"10-10-2010\",\"tags\" : [\"tag 1\",\"tag 2\",\"tag 3\"]}],\"Contacts\" : [{\"name\" : \"John Smith\",\"date\" : \"10-10-2010\",\"tags\" : [\"tag 1\",\"tag 2\",\"tag 3\"]}]}";

    try {
        JSONObject jsonObj    = new JSONObject(jsonString);     // create a json object from a string
        JSONArray  jsonEvents = jsonObj.getJSONArray("Events"); // get all events as json objects from Events array

        for(int i = 0; i < jsonEvents.length(); i++){
            JSONObject event = jsonEvents.getJSONObject(i); // create a single event jsonObject
            Log.e(TAG, "Event name:" + event.getString("name") + " date: " + event.getString("date"));


            JSONArray eventTags = event.getJSONArray("tags");

            for(int j = 0; j < eventTags.length(); j++){
                Log.e(TAG, "Event tag: " + eventTags.getString(j));
            }

        }           

    } catch (JSONException e) {
        e.printStackTrace();
    }

Be aware: Your JSON Object(from your question) will throw a exception because it is not valid( I'm not sure, but it look like a javascript object). You have to add some quotes to each property(key) and ecape them with \ (\").
This tool is really nice to test if a JSON String is valid or not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文