I'm using FlexJSON(but I'm open to other libraries) and I want to manually build a json array. I have certain things that I need to add that are not part of the model that is being serialized. For instance I want to add an html column and css column to my json array. This data would be determined by iterating through the list and seeing if the values are above or below a certain number.
Right now I just have this.
JSONSerializer json = new JSONSerializer();
json.transform(new DateTransformer("MM/dd/yyyy hh:mm:ss"), "timeStamp");
json.transform(new DecimalTransformer("#.00") , "ounces");
json.include("timeStamp", "ounces");
json.exclude("*");
json.prettyPrint(t开发者_高级运维rue);
response.setContentTypeIfNotSet("application/json");
response.out.write(json.serialize(list).getBytes());
But I want to manually build this array instead of just calling serialize. Say the ounces number is below a certain number then that should change the value of the css column. The css column is not part of the object(model) so I need to manually add that too. Thanks.
Flexjson, and other JSON serialization libraries, use the structure of the model as their guide so they work best when the model has the data you want to put into JSON. Flexjson will use the property methods (getter/setter) during serialization. So if you want to add computations like what you were saying you can add getCssColumn() property method and Flexjson will treat it as any old property:
public String getCssColumn() {
return ounces < SOME_THRESHOLD ? "tooSmall" : "justRight";
}
So you can add as many of those methods as you want to your object, and it will serialize them just as they were actual instance variables on your object. This is a nice trick to render computed values into your JSON output just as you are looking for.
If you don't like that then I'd suggest creating a wrapper object that wraps your model object to keep track of the data you want to add to the model. You'll have to be flexible on the JSON output, but you can wrap values around it. You just might end up with something like this:
{
"cssColumn": "justRight",
...
"data": {
"ounces": 45,
...
}
}
Where data points to your model object hence it's down a level from the root. This option is going to consume a little more memory, and require a little more structure (aka more classes to write) to work so I'd prefer the 1st option if it was me.
精彩评论