我目前正在处理一个Android项目,该项目要求我调用一个Web服务,该服务将为我返回一个json文件.我一直在使用gson库解析所有的json文件,并获得一个JSON对象.它一直工作得很好,直到我遇到这个json数据,它的关键字段是动态的.此文件的示例如下所示:

{ "0": { "count":"5"},
  "1": { "title":"...", "desc":"" },
  "2": { "title":"...", "desc":"" },
  "3": { "title":"...", "desc":"" },
  "4": { "title":"...", "desc":"" },
  "5": { "title":"...", "desc":"" },
  "routes": { "route1":"...", "route3":"" },
}

I am able to get the count based on the key id of "0", but I am not sure how do I make use of this value to get the other key objects (key id 1-5), which consist of the data that I needed. Will really appreciate if anyone is able to help me in this matter. Thanks.

推荐答案

The most straightforward approach I can think of is to just treat the structure as a Map (of Map).

对于Gson,这相对容易做到,只要Map struct 是静态已知的,根的每个分支都有相同的深度,所有的东西都是String.

import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GsonFoo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Type mapType = new TypeToken<Map<String,Map<String, String>>>() {}.getType();
    Map<String,Map<String, String>> map = gson.fromJson(new FileReader("input.json"), mapType);
    System.out.println(map);

    // Get the count...
    int count = Integer.parseInt(map.get("0").get("count"));

    // Get each numbered entry...
    for (int i = 1; i <= count; i++)
    {
      System.out.println("Entry " + i + ":");
      Map<String, String> numberedEntry = map.get(String.valueOf(i));
      for (String key : numberedEntry.keySet())
        System.out.printf("key=%s, value=%s\n", key, numberedEntry.get(key));
    }

    // Get the routes...
    Map<String, String> routes = map.get("routes");

    // Get each route...
    System.out.println("Routes:");
    for (String key : routes.keySet())
      System.out.printf("key=%s, value=%s\n", key, routes.get(key));
  }
}

For more dynamic Map structure handling, I strongly suggest switching to use Jackson, instead of Gson, as Jackson will deserialize any JSON object of any arbitrary complexity into a Java Map, with just one simple line of code, and it will automatically retain the types of primitive values.

import java.io.File;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    ObjectMapper mapper = new ObjectMapper();
    Map map = mapper.readValue(new File("input.json"), Map.class);
    System.out.println(map);
  }
}

The same can be achieved with Gson, but it requires dozens of lines of code. (Plus, Gson has other shortcomings that make switching to Jackson well worth it.)

Json相关问答推荐

带有PowerShell内核的NewtonSoft json.Net的奇怪行为

Python将Pandas转换为嵌套的JSON

如何让JSON子查询在没有行的情况下返回空数组而不是NULL

对一些JSON模式验证的混淆

PostgreSQL:删除 JSONB 数组中每个元素的特定键

在 python 中循环 JSON 数组

根据值过滤输入的JSON并使用它准备预期的输出

Groovy JsonBuilder 在for循环中添加数组元素

如何使用 jq 在连续的 json 记录流上调用操作

打印与 JSON 和 PowerShell 中的模式匹配的子项的父项名称

jq: Select 何时来自另一个数组的值与此 json 中的值匹配

转义 Haskell 记录的字段

ORA-01422: 精确提取返回的行数超过了与 json 对象组合的请求数

从 json 对象中过滤掉所有出现的给定属性

Spring MVC 4:application/json内容类型设置不正确

Jackson Scala 模块的小例子?

如何在 Perl 中将简单的哈希转换为 json?

使用绝对或相对路径在 curl 请求中发送 json 文件

在android中使用GSON解析带有动态key和value的JSON

使用 JSONArray 和 JSONObject 进行 Foreach