我有一个包含SpellingError对象数组的JSON字符串。 我使用Gson将其转换为SpellingErrors列表。 解析工作正常(或者至少ddoes不会抛出任何parsinig错误)。但是,当我尝试迭代我希望的SpellingErrors列表时,我发现它们实际上是StringMaps,我得到了错误 “com.google.gson.internal.StringMap无法转换为SpellingError”
知道使用Gson从JSON字符串中提取对象数组的正确方法是什么?我可以看到数组中有3个StringMap对象代表我的3个对象。
以下是有问题的代码
spellingErrorsJSON = "[{\"context\":\"This is a stmple string\",\"errorIndex\":\"3\"},{\"context\":\"This is a stmple string 2\",\"errorIndex\":\"3\"},{\"context\":\"This is a stmple string 3\",\"errorIndex\":\"3\"}]";
List<SpellingError>spellingErrors;
spellingErrors = m_gson.fromJson( spellingErrorsJSON, List.class );
for( SpellingError spellingError : spellingErrors )
{
if( spellingError.isValid() )
{
String spellingMistake = spellingError.getSpellingMistake();
String[] suggestions = Query.lookupSpelling( spellingMistake, LOCALE_US);
}
}
但是如果我使用
m_gson.fromJson( spellingErrorsJSON, SpellingError[].class );
然后我得到一个解析异常 “预计BEGIN_OBJECT但是BEGIN_ARRAY”
这是我的SpellingError PoJo
public class SpellingError
{
private String [] context;
private int errorIndex;
public String[] getContext()
{
return context;
}
public void setContext(String[] context)
{
this.context = context;
}
public int getErrorIndex()
{
return errorIndex;
}
public void setErrorIndex(int index)
{
this.errorIndex = index;
}
}
答案 0 :(得分:0)
您可以使用TypeToken告诉Gson,您希望在结果列表中包含哪种类型的对象。 替换你的行
spellingErrors = m_gson.fromJson( spellingErrorsJSON, List.class );
与
Type collectionType = new TypeToken<List<SpellingError>>(){}.getType();
spellingErrors = m_gson.fromJson( spellingErrorsJSON, collectionType );
编辑:这对我有用:
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
class SpellingError
{
private String context;
private int errorIndex;
public String getContext()
{
return context;
}
public void setContext(String context)
{
this.context = context;
}
public int getErrorIndex()
{
return errorIndex;
}
public void setErrorIndex(int index)
{
this.errorIndex = index;
}
}
public class TestGson {
private static Gson m_gson = new Gson();
class DataPacket {
public String fn;
public Object data;
}
class ChatPacket {
public int roomId;
public String message;
}
public static void main(String[] args) {
String spellingErrorsJSON = "[{\"context\":\"This is a stmple string\",\"errorIndex\":\"3\"},{\"context\":\"This is a stmple string 2\",\"errorIndex\":\"3\"},{\"context\":\"This is a stmple string 3\",\"errorIndex\":\"3\"}]";
List<SpellingError>spellingErrors;
Type collectionType = new TypeToken<List<SpellingError>>(){}.getType();
spellingErrors = m_gson.fromJson( spellingErrorsJSON, collectionType );
for( SpellingError spellingError : spellingErrors )
{
String spellingMistake = spellingError.getContext();
}
}
}