我有一个像下面的对象列表
List<ProductInfo>
我想使用flex json序列化它,以便它应该
[{"product_id":"2","name":'stack"'},{"product_id":"2","name":"overflow"}]"
用于从上面的字符串反序列化为对象列表我正在使用以下代码
final List<ProductInformation> productInformationList = new JSONDeserializer<List<ProductInformation>>().use(null, ArrayList.class)
.use("values", ProductInformation.class).deserialize(parameterValue);
将对象序列化为字符串我这样做但它不起作用....我错过了一些东西......
final String serializizedString = new JSONSerializer().serialize(productInformationList);
将对象序列化为字符串需要什么?
答案 0 :(得分:3)
List<ProductInfo> ls = new JSONDeserializer<ArrayList<ProductInfo>>().use("values", ProductInfo.class).deserialize(s);
请遵循此link或完全按照
阅读地图和收藏集的重构路径列表。在以前的版本中,无法同时指定Collection / Map的具体顶部和其中包含的具体类。路径语言不够冗长。现在,您可以指定具体集合和其中包含的具体类。如果person.friends是指向java.util.Map的路径。例如,
new JSONDeserializer<Person>()
.use( "person.friends", HashMap.class )
.use("person.friends.keys", Relation.class )
.use( "person.friends.values", Person.class )
通过向路径person.friends添加“keys”和“values”,您可以指定用于Map的键和值的实际具体类。对于集合,您只需附加“值”即可指定包含的类。例如:
new JSONDeserializer<List<Person>>().use( "people", ArrayList.class ).use("people.values", Person.class )
答案 1 :(得分:1)
我以前从未和flexjson玩过,但在下载之后,在这里玩它就是我想出来的:
public class TestFlexJson {
public static void main(String args[]) {
ProductInfo p1 = new ProductInfo(1, "Stack");
ProductInfo p2 = new ProductInfo(2, "Overflow");
List<ProductInfo> infos = Arrays.asList(p1, p2);
String s = new JSONSerializer()
.exclude("*.class", "description")
//.include("productId", "name")
// EDIT: the "include" call is irrelevant for this example.
.serialize(infos);
System.out.println(s);
// => [{"name":"Stack","productId":1},{"name":"Overflow","productId":2}]
List<ProductInfo> ls = new JSONDeserializer<List<ProductInfo>>().deserialize(s);
System.out.println(ls);
// => [{name=Stack, productId=1}, {name=Overflow, productId=2}]
}
public static class ProductInfo {
private int id;
private String name;
private String desc; // Not used, to demonstrate "exclude".
public ProductInfo(int id, String name) {
this.id = id;
this.name = name;
}
public int getProductId() { return this.id; }
public String getName() { return this.name; }
public String getDescription() { return this.desc; }
}
}
似乎适合我。
答案 2 :(得分:1)
不幸的是,如果需要将json反序列化为集合,则必须包含类属性。在上面的例子中,json字符串被反序列化如下:
List<ProductInfo> ls = new JSONDeserializer<List<ProductInfo>>().deserialize(s);
System.out.println(ls);
// => [{name=Stack, productId=1}, {name=Overflow, productId=2}]
如果您尝试直接访问某个元素,请说ls.get(0)
,您会收到ClassCastException: java.util.HashMap cannot be cast to ProductInfo
。
您必须序列化对象以包含类属性,以便适当地反序列化为集合。