我能想到的最直接的方法是将结构视为Map(Map)。

使用Gson,这是相对容易的,只要Map结构是静态已知的,来自根的每个分支都具有相同的深度,并且所有内容都是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>>() {}.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));

}

}对于更加动态的Map结构处理,我强烈建议切换到使用Jackson而不是Gson,因为Jackson会将任意复杂度的任何JSON对象反序列化为Java Map,只需一行简单的代码,它就会自动保留类型原始价值观。

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);

}

}使用Gson可以实现同样的目标,但它需要几十行代码。 (另外,Gson还有其他缺点,让切换到杰克逊非常值得。)

更多推荐