views:

418

answers:

1

Hi -

New to java, but would love to implement my working jsp that generates xml used by a lovely jquery flexigrid to use a json version (generated by gson). I'm just starting out w/ java basically, but would like to learn the best way to do this. I've been looking at inner classes, but wanted to check out what would be considered best practice.

The json expected format (I got this from another post here) is:

total: (no of rec)
 page : (page no)
 rows : {id: 1, cell: [ (col1 value) , (col2 value) ,.. ] },
        {id: 2, cell: [ (col1 value) , (col2 value) ,.. ] }

And, so far my non compilable java is:

private class _JsonReturn {
    int page ;
    int total ;
    class Rows {
        String id = new String();
        MultiMap cell = new MultiValueMap() ;
        private Rows( String newCell ) {
            this.id = newCell ;
        }
        private void _addRowValue( String cellValue ){
            this.cell.put( this.id, cellValue );
        }
        private Object _getRows() {
            return this ;
        }

    }      
}

Help - I think I'm over complicating things here! Thanks a ton in advance!

A: 

Xstream is a very handly and useful library to marshall java classes or POJO to xml or json. And it also very fast.

EDIT For your java structure requeriments, I propose you a simple structure (perhaps I get a -1, but it's the simplest :)

Vector rowsVector = new Vector();
Map row = new HashMap();
row.put("id", "1");
row.put("cellValue", "Hola");
rowsVector.add(row);

Map mapToJson = new HashMap();
mapToJson.put("page", 3);
mapToJson.put("total", rowsVector.size());
mapToJson.put("rows", rowsVector);

Then you can parse it with any JsonParser. I hope it helps you :)

Aito
Thanks - I could use Xstream - it looks good. But I'm having a problem first defining the java object that I want to translate.
emmtqg
You could simply create a java.util.Map (perhaps HashMap), what is the best approach to a JSONObject (key/value). For your rows, set a Vector/Array of java.util.Maps.
Aito
I could - the vector of maps - that what I was trying with the multimap. Would the multimap not be simpler? For the json write (w/ any library) would the vector of maps be better because of the json output requirement? I appreciate the help! (Sorry for delayed response - working on getting to know netbeans :) ).
emmtqg
I edit to show you an alternative. I don't know how the commons json's parser handle the multimap. I often do the 'map-vector-to-json' stuff, for simple requeriments, and it works fine.
Aito
Thanks so much Aito. It did - I did manage to start to get the Json object the way I needed it - then 3 classes later realized I was making it much to complicated. I really like your solution alot better - no -1 for simplicity - simple is more elegant! Thank you!
emmtqg