Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 一个json参数包含数组或对象中的数据。如何使用GSON检查数据是数组还是对象_Android_Gson - Fatal编程技术网

Android 一个json参数包含数组或对象中的数据。如何使用GSON检查数据是数组还是对象

Android 一个json参数包含数组或对象中的数据。如何使用GSON检查数据是数组还是对象,android,gson,Android,Gson,我有无法更改的web服务。因此,我有一个名为content的参数。此参数包含数组或对象的数据。我的意思是有时我得到数组格式的数据,有时我得到对象格式的数据 我正在使用gson库()解析json。我已经创建了一个自定义类,并在这里使用了该参数 class { @SerializedName("content") private List<Content> content; public List<Content> getContent() {

我有无法更改的web服务。因此,我有一个名为content的参数。此参数包含数组或对象的数据。我的意思是有时我得到数组格式的数据,有时我得到对象格式的数据

我正在使用gson库()解析json。我已经创建了一个自定义类,并在这里使用了该参数

class {

@SerializedName("content")
    private List<Content> content;

  public List<Content> getContent() {
        return content;
    }

    public void setContent(List<Content> content) {
        this.content = content;
    }
更新:

当paramcontent为数组时,则解析正确。但是当内容参数在字符串中时。我犯了一个错误

 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 410 path $.response.content
我用的是TypeAdapterFactory

  public class ArrayAdapterFactory implements TypeAdapterFactory {

    @Override
    @SuppressWarnings("unchecked")
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

        if (type.getRawType()!= Templetegt4StoryResponse.Response.Content.class) return null;

        TypeAdapter<Templetegt4StoryResponse.Response.Content> defaultAdapter = (TypeAdapter<Templetegt4StoryResponse.Response.Content>) gson.getDelegateAdapter(this, type);

        TypeAdapter<T> typeAdapter = (TypeAdapter<T>) new AddressAdapter(defaultAdapter);
        return typeAdapter;

        //return (TypeAdapter<T>) new AddressAdapter(defaultAdapter);
    }

}


public class AddressAdapter extends TypeAdapter<Templetegt4StoryResponse.Response.Content> {

    protected TypeAdapter<Templetegt4StoryResponse.Response.Content> defaultAdapter;

    /**
     * @param defaultAdapter
     */
    public AddressAdapter(TypeAdapter<Templetegt4StoryResponse.Response.Content> defaultAdapter) {
        this.defaultAdapter = defaultAdapter;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void write(JsonWriter out, Templetegt4StoryResponse.Response.Content value) throws IOException {
        defaultAdapter.write(out, value);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Templetegt4StoryResponse.Response.Content read(JsonReader in) throws IOException {
        System.out.println("in.peek = "+in.peek());

        if (in.peek()==JsonToken.STRING) {
            in.skipValue();
            return null;
        }
        System.out.println("in.peek = "+in.peek());

        return defaultAdapter.read(in);
   }

在GSON中,您可以使用自定义序列化程序

像这样创建一个自定义类型适配器

class ArrayAdapter<T> extends TypeAdapter<List<T>> {

    private Class<T> adapterclass;

    public ArrayAdapter(Class<T> adapterclass) {
        this.adapterclass = adapterclass;
    }

    @Override
    public List<T> read(JsonReader reader) throws IOException {

        List<T> list = new ArrayList<T>();
        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();

        final JsonToken token = reader.peek();
        // Handling of Scenario 2( Check JavaDoc for the class) :
        if (token == JsonToken.STRING || token == JsonToken.NUMBER ||
                token == JsonToken.BOOLEAN) {
            T inning = (T) gson.fromJson(reader, adapterclass);
            list.add(inning);
        } else if (token == JsonToken.BEGIN_OBJECT) {
            // Handling of Scenario 1(Check JavaDoc for the class) :
            T inning = (T) gson.fromJson(reader, adapterclass);
            list.add(inning);
        } else if (token == JsonToken.BEGIN_ARRAY) {
            reader.beginArray();
            while (reader.hasNext()) {
                @SuppressWarnings("unchecked")
                T inning = (T) gson.fromJson(reader, adapterclass);
                list.add(inning);
            }
            reader.endArray();
        }

        return list;
    }

    @Override
    public void write(JsonWriter writer, List<T> value) throws IOException {

    }


}

对但我使用的是GSON图书馆。而且在课堂上也做过切割。所以我不能把逻辑放在这里。你检查我的答案了吗?@Krish谢谢Krish。我更新了我的问题。当param包含数组时,它的解析是正确的。但当content参数是字符串时。我犯了一个错误。com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为BEGIN_数组,但在第1行第410列的字符串路径$。response.content kinldy具有look@Krish请检查并尝试这个逻辑
  Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();
 return gson.fromJson(str, Templetegt4StoryResponse.class);


public class Templetegt4StoryResponse {

  @SerializedName("content")
    private List<Content> content;


  public class Content{

        @SerializedName("sequence_no")
        private String sequence_no;

        @SerializedName("is_url_code")
        private String is_url_code;
}
content: [
{
sequence_no: "1",
is_url_code: "is_url",
}
]


content: "this is new text",
if (json instanceof JSONObject)
  //you have an object
else if (json instanceof JSONArray)
  //you have an array
class ArrayAdapter<T> extends TypeAdapter<List<T>> {

    private Class<T> adapterclass;

    public ArrayAdapter(Class<T> adapterclass) {
        this.adapterclass = adapterclass;
    }

    @Override
    public List<T> read(JsonReader reader) throws IOException {

        List<T> list = new ArrayList<T>();
        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();

        final JsonToken token = reader.peek();
        // Handling of Scenario 2( Check JavaDoc for the class) :
        if (token == JsonToken.STRING || token == JsonToken.NUMBER ||
                token == JsonToken.BOOLEAN) {
            T inning = (T) gson.fromJson(reader, adapterclass);
            list.add(inning);
        } else if (token == JsonToken.BEGIN_OBJECT) {
            // Handling of Scenario 1(Check JavaDoc for the class) :
            T inning = (T) gson.fromJson(reader, adapterclass);
            list.add(inning);
        } else if (token == JsonToken.BEGIN_ARRAY) {
            reader.beginArray();
            while (reader.hasNext()) {
                @SuppressWarnings("unchecked")
                T inning = (T) gson.fromJson(reader, adapterclass);
                list.add(inning);
            }
            reader.endArray();
        }

        return list;
    }

    @Override
    public void write(JsonWriter writer, List<T> value) throws IOException {

    }


}
public class ArrayAdapterFactory implements TypeAdapterFactory {

    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {

        TypeAdapter<T> typeAdapter = null;
        try {
            if (type.getRawType() == ArrayList.class) {

                typeAdapter = new ArrayAdapter((Class) ((ParameterizedType) type.getType()).getActualTypeArguments()[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return typeAdapter;

    }

}
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();