{"menus":[{"key":"测试1","type":"Channel","owner":"","title":"标题1","fav":"false","lineSelect":"false","chartSelect":"false"},{"key":"测试2","type":"Channel","owner":"","title":"标题2","fav":"false","lineSelect":"false","chartSelect":"false"},{"key":"测试3","type":"Channel","owner":"","index":"1","title":"标题3","fav":"false","lineSelect":"false","chartSelect":"false"}]}
以上是一个复杂json串,其中menus作为key的值又是一个json数组,我们首先考虑将menus和后面的值分开,采用Map接收;后面的json数组采用List接收;再往里边的json串用Map或实体类接收。
综上分析,代码实现为:
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.List; import java.util.Map; public class JsonTest { public static void main(String[] args) { String str = "{\"menus\":[{\"key\":\"测试1\",\"type\":\"Channel\",\"owner\":\"\",\"title\":\"标题1\",\"fav\":\"false\",\"lineSelect\":\"false\",\"chartSelect\":\"false\"},{\"key\":\"测试2\",\"type\":\"Channel\",\"owner\":\"\",\"title\":\"标题2\",\"fav\":\"false\",\"lineSelect\":\"false\",\"chartSelect\":\"false\"},{\"key\":\"测试3\",\"type\":\"Channel\",\"owner\":\"\",\"index\":\"1\",\"title\":\"标题3\",\"fav\":\"false\",\"lineSelect\":\"false\",\"chartSelect\":\"false\"}]}"; Gson gson = new Gson(); Map<String, List<Map<String, String>>> map = gson.fromJson(str, new TypeToken<Map<String, List<Map<String, String>>>>(){}.getType()); Map<String, List<JsonTestEntity>> map2 = gson.fromJson(str, new TypeToken<Map<String, List<JsonTestEntity>>>(){}.getType()); System.out.println(); } }
其中,实体类的定义为:
public class JsonTestEntity { private String key; private String type; private String owner; private String title; private String fav; private String lineSelect; private String chartSelect; }
解析完成,如有其它问题欢迎留言沟通。
文章来源: 复杂json的转换