I have been using GSON library to parse all the json string and get a JSON object.
But now I need to parse is like this:
{
"status":1,
"info":[
{
"\u5a31\u4e50":"\u51b7\u76d8,\u9ad8\u811a\u676f,\u6211\u7684\u7cd6\u679c\u5c4b,\u670d\u52a1\u4e1a\u6d88\u8d39\u52b5"
},
{
"\u7f8e\u5986":"\u4e2a\u62a4|\u5316\u5986#\u9762\u90e8\u62a4\u7406,\u4e2a\u4eba\u536b\u751f,\u8eab\u4f53\u62a4\u7406,\u9999\u6c34\u9999\u6c1b,\u6c90\u6d74|\u7f8e\u53d1\u7528\u54c1,\u5f69\u5986,\u7cbe\u6cb9SPA,\u773c\u90e8\u62a4\u7406,\u78e8\u7802\u53bb"
},
{
"\u8863\u670d":"\u670d|\u9970|\u978b|\u5e3d#\u670d\u88c5,\u978b\u9774,\u5185\u8863,\u914d\u9970,\u536b\u8863,\u4f11\u95f2\u88e4,T\u6064,\u88d9\u5b50,\u886c\u886b,\u9488\u7ec7\u886b,\u5a74\u5e7c\u513f\u670d\u9970"
}
],
"total":3
}
The key fields are dynamic, so I don’t know how to write a model class to read this.
How would you like your model class to look?
statusandtotalwould probably beint, so that only leavesinfo.As an experiment, just add a field
Object infoand see how Gson would set it to anArrayList<LinkedHashMap<String, String>>— ugly and hard to access by key, but all the data is there. Given that information, the fastest way to model a class would be:If you have control over how that JSON is generated, I suggest changing the structure of
infofrom an array of objects[{a:b},{c:d},{e:f}]to just an object{a:b,c:d,e:f}. With this, you could just map it to aMap<String, String>with all the benefits like access by key,keys()andvalues():If you want the latter model class without changing the JSON format, you’ll have to write a
TypeAdapter(orJsonDeserializerif you’re only interested in parsing JSON, not generating it from your model class).Here’s a JsonDeserializer hat would map your original
infoJSON property to a plainMap<String, String>.You need to register this custom
JsonDeserializersimilar to this:Note that this registers the custom deserializer for any
Map<String, String>regardless in what class it is encountered. If you don’t want this, you’ll need to create a customTypeAdapterFactoryas well and check the declaring class before returning and instance of the deserializer.