I’ve been trying to use XStream to generate JSONto be consumed by Dojo. But I can’t find the way to generate the right JSON from XStream, it keeps adding extraneous {} around. I even tried this but no luck . For example I want to generate this JSON output (taken from Dojo FilteringSelect example) :
I couldn’t figure out how to get XStream to output the desired JSON. The main issue is that I couldn’t make “items” a simple JSON array, it always end up as an object with an array in it. So I decided to give out a try to FLEXJSON. I really found much easier to control the output with this tool. I guess that XStream is more focused on serialization/deserialization and doesn’t allow customization without relaying in custom converters (I didn’t walk that road, too much work). Here is the example source code (also as a gist) using FLEXJSON:
123456789101112131415161718
package com.rubenlaguna.json.flexjson;
import flexjson.JSONSerializer;
public class WriteFlexjsonDojoTest {
public static void main(String[] args) {
ItemCollection itemCollection = new ItemCollection("abbreviation");
itemCollection.add(new Item("Alaska", "Alaska", "AK"));
itemCollection.add(new Item("Wyoming", "Wyoming", "WY"));
JSONSerializer serializer = new JSONSerializer().include("items").exclude("*.class");
String correctJsonStr = serializer.serialize(itemCollection);
System.out.println(correctJsonStr);
}
}