Anurag
Anurag

Reputation: 227

Parsing json object in java code

I am stuck with code actually i am using spring MVC 4. I have one condition where i need to pass the json object at controller side an iterate it. My Json object look like below

{"comptocome":[
    {"1":"Key Parameters","2":"Cellular Limited","3":"limited","4":"Cellular Limited"},
    {"1":"- Long term","2":"Reaffirmed","3":"football","4":"golf"}
    ]
}

with respect to above i have pass this to controller and iterate according to the number of row for example from above two times loop and also to fetch data as per key can any one help me out sort this problem with help of import org.json.simple.JSONObject package.

Thanks in advance.

Upvotes: 0

Views: 186

Answers (2)

Gowtham Ravi
Gowtham Ravi

Reputation: 21

Parse using Jackson JSON

eg:

{
"foo" : ["1","2","3","4"],
"bar" : "xxxx",
"baz" : "yyyy"
}

Could be mapped to this class:

public class Fizzle{
    private List<String> foo;
    private boolean bar;
    private int baz;
    // getters and setters omitted
}

Now if you have a Controller method like this:

@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
    return new Fozzle(input);
}

Upvotes: 1

prsmax
prsmax

Reputation: 223

You can use com.google.gson for it:

@RequestMapping(value = "/request", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseClass addDeparturePoint(@RequestBody String request) {
    Gson gson = new Gson();
    RequestClass request = gson.fromJson(request, RequestClass.class);
    ResponseClass response = buildResponce(request);
    return response;

}

Upvotes: 0

Related Questions