Gson处理对象或数组

Gson处理对象或数组

本文介绍了Gson处理对象或数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的类

  public class MyClass {
private List< MyOtherClass>其他;
}

public class MyOtherClass {
private String name;
}

我的JSON可能看起来像这样

  {
others:{
name:val
}
}

或者这个

  { 
其他:[
{
名称:val
},
{
名称:val
}
]
}

我希望能够使用相同的 MyClass 这两种JSON格式。有没有办法与Gson做到这一点?

解决方案

我想出了一个答案。

private static class MyOtherClassTypeAdapter implements JsonDeserializer< List< MyOtherClass>> {
公共列表< MyOtherClass>反序列化(JsonElement json,类型typeOfT,JsonDeserializationContext ctx){
List< MyOtherClass> vals = new ArrayList< MyOtherClass>(); (),
if(json.isJsonArray()){
for(JsonElement e:json.getAsJsonArray()){
vals.add((MyOtherClass)ctx.deserialize(e,MyOtherClass.class) );

} else if(json.isJsonObject()){
vals.add((MyOtherClass)ctx.deserialize(json,MyOtherClass.class));
} else {
throw new RuntimeException(Unexpected JSON type:+ json.getClass());
}
返回vals;




$ b $ p $实例化一个像这样的Gson对象$ / $ p

 键入myOtherClassListType = new TypeToken< List< MyOtherClass>>(){} .getType(); 

Gson gson = new GsonBuilder()
.registerTypeAdapter(myOtherClassListType,new MyOtherClassTypeAdapter())
.create();

TypeToken 是一个 com.google.gson.reflect.TypeToken



您可以在此阅读有关解决方案:




I've got the following classes

public class MyClass {
    private List<MyOtherClass> others;
}

public class MyOtherClass {
    private String name;
}

And I have JSON that may look like this

{
  others: {
    name: "val"
  }
}

or this

{
  others: [
    {
      name: "val"
    },
    {
      name: "val"
    }
  ]
}

I'd like to be able to use the same MyClass for both of these JSON formats. Is there a way to do this with Gson?

解决方案

I came up with an answer.

private static class MyOtherClassTypeAdapter implements JsonDeserializer<List<MyOtherClass>> {
    public List<MyOtherClass> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
        List<MyOtherClass> vals = new ArrayList<MyOtherClass>();
        if (json.isJsonArray()) {
            for (JsonElement e : json.getAsJsonArray()) {
                vals.add((MyOtherClass) ctx.deserialize(e, MyOtherClass.class));
            }
        } else if (json.isJsonObject()) {
            vals.add((MyOtherClass) ctx.deserialize(json, MyOtherClass.class));
        } else {
            throw new RuntimeException("Unexpected JSON type: " + json.getClass());
        }
        return vals;
    }
}

Instantiate a Gson object like this

Type myOtherClassListType = new TypeToken<List<MyOtherClass>>() {}.getType();

Gson gson = new GsonBuilder()
        .registerTypeAdapter(myOtherClassListType, new MyOtherClassTypeAdapter())
        .create();

That TypeToken is a com.google.gson.reflect.TypeToken.

You can read about the solution here:

https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener

这篇关于Gson处理对象或数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:12