当json中的key值为数字时,怎么用GSON解析?

一般json中的key值都是固定的,但如果key值为数字序列时应该怎么办呢?如下

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

在这里,最常用的方法是将这段json解析为Map结构:

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>>() {}.getType();
    Map> 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 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 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循环 中,如果json中没有“count”那行怎么办呢?

可以先用 JSONObject 取出主要数据,用 i <= JSONObject.length 代替到 i <= count 处就可以了~

你可能感兴趣的:(Android)