2016-12-19 191 views
-1

我在GSON中使用了GSON作为JSON解析器,但密钥并不总是相同的。例如, 。我有以下JSON:使用gson解析json树

{ 
     "message":"....", 
     "categories_sorted": [ 
      { 
       "550e8400-e29b-41d4-a716-446655440000": [ 
       { 
        "550e8400-e29b-41d4-a716-446655443333": [ 
        { 
         "550e8400-e29b-41d4-a716-446655448964": [] 
        } 
        ] 
       }, 
       { 
        "550e8400-e29b-41d4-a716-446655443334": [] 
       } 
       ] 
      }, 
      { 
       "550e8400-e29b-41d4-a716-446655440023": [ 
       { 
        "550e8400-e29b-41d4-a716-446655442344": [] 
       } 
       ] 
      } 
      ] 
     } 

我需要解析这棵树“categories_sorted”。我的Java POJO对象:

public class CategoryPOJO { 

    @SerializedName("message") 
    @Expose 
    private String message; 

    @SerializedName("categories_sorted") 
    @Expose 
    private JsonArray sortedCategoryItems; 

....... 
Getters and setters 
} 
+0

我发现决策的近似版本,但他们并不在我的情况下工作 链接:[链接](https://gist.github.com/patrickbaumann/897492) –

回答

-1

看到jsonschema2pojo.org资源用于获取POJO类(选择GSON和JSON选项)

+0

我以前见过这个资源。 但它不适合我,因为我的钥匙是动态的 –

0

你要做这个ReferenceLink GSON解串器的方法。你必须定制像这样只是举例:

@Override 
public User deserialize(JsonElement json, Type type, 
         JsonDeserializationContext context) throws JsonParseException { 

     return new CategoryPOJO(
      json.getAsJsonPrimitive().getAsInt(), 
      json.getAsString(), 
      json.getAsInt(), 
      (CategoryPOJO)context.deserialize(json.getAsJsonPrimitive(), 
      CategoryPOJO.class)); 
}