我有以下课程:
public class MyProperty
{
public String Key;
public String Value;
}
public class MyModel
{
public String Name;
public List<MyProperty> Properties;
}
当我尝试像这样序列化MyObject
类型的对象时:
MyModel m = new MyModel(){{
Name="aaaa";
Properties = new ArrayList<MyProperty>();
}};
m.Properties = new ArrayList<MyProperty>();
m.Properties.add(new MyProperty() {{ Key="a"; Value="1"; }});
m.Properties.add(new MyProperty() {{ Key="b"; Value="11"; }});
m.Properties.add(new MyProperty() {{ Key="c"; Value="111"; }});
String json1 = g.toJson(m, MyModel.class);
我得到以下结果:
{"Name":"aaaa","Properties":[null,null,null]}
为什么当源对象肯定不为空时,属性列表被序列化为null列表?
字符串的反序列化
{"Name":"aaaa","Properties":[{"Key":"a","Value":"1" etc }]}
工作正常。
答案 0 :(得分:0)
您可能遇到的问题是多态性 - 您的模型表明属性属于&#34; MyProperty&#34;但是你的代码片段使用&#34; SyncProperty&#34;。与Gson有关的一些问题 - 看看这里的讨论:How to handle deserializing with polymorphism?
答案 1 :(得分:0)
我会告诉您为什么code
有您要查找的输出而不是您所问的code
。
代码
import java.util.ArrayList;
import com.google.gson.Gson;
public class TestOneDrive {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyModel model = new MyModel();
model.setName("someName");
ArrayList<MyProperty> myProperties = new ArrayList<>();
for (int i = 0; i < 5; i++) {
MyProperty myProperty = new MyProperty();
myProperty.setKey("Key_" + i);
myProperty.setValue("Value_" + i);
myProperties.add(myProperty);
}
model.setProperties(myProperties);
String result = (new Gson()).toJson(model);
System.out.println("" + result);
}
}
class MyProperty {
public String Key;
public String Value;
public String getKey() {
return Key;
}
public void setKey(String key) {
Key = key;
}
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
}
}
class MyModel {
public String Name;
public ArrayList<MyProperty> Properties;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public ArrayList<MyProperty> getProperties() {
return Properties;
}
public void setProperties(ArrayList<MyProperty> properties) {
Properties = properties;
}
}
输出
{
"Name": "someName",
"Properties": [
{
"Key": "Key_0",
"Value": "Value_0"
},
{
"Key": "Key_1",
"Value": "Value_1"
},
{
"Key": "Key_2",
"Value": "Value_2"
},
{
"Key": "Key_3",
"Value": "Value_3"
},
{
"Key": "Key_4",
"Value": "Value_4"
}
]
}