Java Gson格式错误斜杠上出现异常
我正在尝试用Gson反序列化一个类 这是我正在尝试反序列化的类:Java Gson格式错误斜杠上出现异常,java,android,json,deserialization,gson,Java,Android,Json,Deserialization,Gson,我正在尝试用Gson反序列化一个类 这是我正在尝试反序列化的类: public class Product { public String id; public String name; public String expDate; public String iconPath; public Product(final String id, final String name, final String expDate, final String i
public class Product {
public String id;
public String name;
public String expDate;
public String iconPath;
public Product(final String id, final String name, final String expDate, final String iconPath) {
this.id = id;
this.name = name;
this.expDate = expDate;
this.iconPath = iconPath;
}
@Override
public final String toString() {
return new Gson().toJson(this);
}
}
这是使用的代码:
final String serializedProducts = PreferenceManager.getDefaultSharedPreferences(activity).getString("products_" + sectionNumber, null);
if(serializedProducts != null) {
final Gson gson = new GsonBuilder().create();
final List<?> deserializedProducts = gson.fromJson(serializedProducts, List.class);
final List<Product> result = new ArrayList<Product>();
for(final Object product : deserializedProducts) {
//System.out.println(product.toString());
result.add(gson.fromJson(product.toString(), Product.class));
}
}
我在第1行第12列(斜线)有一个异常MalformedJsonException
那么,我如何进行反序列化呢
谢谢;) JSON要求引用字符串值(包括关键字)。JSON的名称/值分隔符是冒号,而不是等号 因此,要成为有效的JSON,文本应为:
{"expDate":"4/6/2014", "iconPath":"/data/.../5000112558265", "id":5000112558265, "name":"Coca-Cola Zéro"}
有关详细信息,请参阅
我刚刚注意到,您的toString
实现使用GSON生成表面上的JSON输出,但要么没有使用toString
方法,要么GSON对有效JSON的构成有非常错误的理解。我的期望是肯定是前者
我现在看到了问题,我想,现在我再仔细看看;无论反序列化对象是什么,它们都不是Product
的实例。因此,以下代码:
for(final Object product : deserializedProducts) {
//System.out.println(product.toString());
result.add(gson.fromJson(product.toString(), Product.class));
不调用Product.toString
,而是调用任何对象gson.fromJson(serializedProducts,List.class)的toString
代码>生成并添加到列表中
您应该向调试输出中添加product.getClass()
,以证明这一点。然后你应该研究如何创建产品的实际实例。我注意到了,但你很快就回答了+1因此,正确的id:notID=@user35736644892:是的,我很惊讶HTML/XML让我们看到name=“some value”
是正常和正确的。我偶尔希望JSON遵循ML属性样式,而不是“name”:“some value”
样式。好的,谢谢,我正在准备中,但是当我使用object.toString()时,它会去掉引号,为什么?当我转到共享的prefs文件时,引号是这样的"://@Skyost:嗯,toString()
的契约不需要任何特定的编码,只需要对象的字符串表示,通常用于日志记录。因此,除非相关对象的toString
被记录为生成该对象的有效JSON表示,否则没有任何连接。@Skyost:至于“共享prefs”,我不这么认为。但是,无论如何,您给出的值,“
(假设您将分号作为输入错误删除),是一个SGML/HTML/XML实体编码,表示双引号,显然与JSON无关。
for(final Object product : deserializedProducts) {
//System.out.println(product.toString());
result.add(gson.fromJson(product.toString(), Product.class));