开发者

Leave off field names using FlexJson, Jackson, GSON etc

Right now I'm using the org.json JSON library.

JSONArray data = new JSONArray();

        for (PkgLoad pkgLoad : list) {
     开发者_JAVA百科       JSONArray row = new JSONArray();
            row.put(Double.parseDouble(df.format(pkgLoad.ounces)));
            row.put(pkgLoad.revolutions);
            data.put(row);
        }
        jsonResponse.put("aaData", data);

This is how I'm building my array. Row by row(I like doing this.) If there is a way to build the data row by row in any other libraries let me know.

Anyway. With that method I get this.

"aaData":[[2.55,6],[2.54,6],[2.53,6],[2.54,6],[2.55,6],[2.52,6],[2.55,6],[2.52,6],[2.54,6],[2.53,6]]}

That's fine. The field names are left off. With the other libraries I get the field names. So it becomes this.

 "aaData":[["ounces" : 2.55, "revolutions" : 6], etc, etc}

How do I omit this fields. Thank you very much.


So with Flexjson you wouldn't duplicate the work you did to build your JSON from the data model (i.e. PkgLoad). If you wanted to convert that object to JSON you'd do something like the following:

List<PkgLoad> packages = new ArrayList<PkgLoad>();
packages.add( new PkgLoad( 24.3, 6 ) );
packages.add( new PkgLoad( 45.3, 5 ) );
packages.add( new PkgLoad( 23.3, 4 ) );
...
String json = new JSONSerializer().serialize( packages, "aaData" );

That would produce JSON like the following:

{ "aaData": [ { "ounces": 24.3, "revolutions": 6 }, { "ounces": 45.3, "revolutions": 5 }, { "ounces": 23.3, "revolutions": 4 } ] }

Why? Because the list object you gave it contained an object inside it that had two fields "ounces" and "revolutions", and that's what you get back.

That's great because it's a single line to encode your JSON without requiring you write a lot of boilerplate code to translate your object model into JSON. The thing you have to be flexible on is that your JSON output will mirror (more or less) your object model design. If you're happy with that Flexjson, gson, and jackson then they will take care of all the mundane tasks of translating your object into JSON for you so you can get back to writing your code.

However, if you have to have a drastically different format of JSON from your object model your best using org.json library and doing it by hand. Trying to tell these libraries how to convert your objects into something like what you posted is going to be as much work to writing it manually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜