2

I have a string:

 [{"product_id":"2","name":'stack"'},{"product_id":"2","name":"overflow"}]"

How can I use Flexjson's JSONDeserializer to obtain all product_ids from the above string?

I have a class called productinformation which has fields like product_id and name.

Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
saurabh ranu
  • 1,351
  • 6
  • 18
  • 24

1 Answers1

11

You could use the JSONDeserializer.use() methods to tell it how to deserialize the array and each object in the array, in this case of class ProductInformation . The product_id attribute does not match up with the standard naming that flexjson expects, so your properties on the object will need to have an underscore in them.

String products= "[{\"product_id\": \"123\",\"name\":\"stack\"},{\"product_id\": \"456\",\"name\":\"overflow\"}]";
List<ProductInformation> productInfoList = new JSONDeserializer<List<ProductInformation> >()
    .use(null, ArrayList.class)
    .use("values",ProductInformation.class)
    .deserialize(products);

for(ProductInformation productInformation : productInfoList){
    System.out.println(productInformation.getProduct_id();
}

The section on "Deserialization Without the Training Wheels" in Deserialization section of the docs goes into additional details on the other cases to consider if the type information is not included in the JSON string.

Rob Tanzola
  • 1,785
  • 14
  • 11
  • 1
    pardon my ignorance but what is meant by--- use ("values",ProductInformation.class)..what is "values"... – saurabh ranu Aug 18 '11 at 17:12
  • 3
    "values" is a specific name that flexjson uses to refer to the members of a collection, in this case the list. This is basically saying "each of the members of this list should be deserialized into a `ProductInformation` object. – Rob Tanzola Aug 18 '11 at 18:14
  • Some minutes ago i have the requirement that to serilize again a list into above string..could u show me some ideas in this direction also... – saurabh ranu Aug 18 '11 at 20:30
  • @ rob : hey i posted a question here http://stackoverflow.com/questions/7122368/how-i-can-serilaize-a-list-of-object-using-flexjson ... if u know the answer please comment there... – saurabh ranu Aug 19 '11 at 17:30