我有無法更改的Web服務。所以我有一個參數叫內容。該參數包含數組或對象的數據。我的意思是有時候我以數組格式獲取數據,有時候我以對象格式獲取數據。一個json參數包含數組或對象中的數據。如何檢查數據是使用GSON的數組或對象
我正在使用gson庫(https://github.com/google/gson)來解析json。我創建了一個自定義類,並在此使用該參數。
class {
@SerializedName("content")
private List<Content> content;
public List<Content> getContent() {
return content;
}
public void setContent(List<Content> content) {
this.content = content;
}
所以當我在數組中獲取數據。沒關係。但它正在爲對象而崩潰。
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 409 path $.response.content
更新:
當PARAM 內容是陣列則解析正確的。但是當內容參數是字符串。我收到錯誤。
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 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;
}
}
這是JSON。內容參數可以採用兩種格式。
content: [
{
sequence_no: "1",
is_url_code: "is_url",
}
]
content: "this is new text",
你檢查我的答案? – Krish
@Krish謝謝克裏什。我更新了我的問題。當param包含數組時,它解析正確。但是當內容參數是字符串時。我收到錯誤。 ** com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:期望BEGIN_ARRAY,但是在第1行第410列路徑$ .response.content ** kinldy看看 – user1629977
@Krish請檢查先生 – user1629977