0

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.

DwB
  • 37,124
  • 11
  • 56
  • 82
Anurag
  • 227
  • 1
  • 5
  • 14
  • 1
    look at this answer: http://stackoverflow.com/a/26719883/1614378 – alex Nov 18 '14 at 14:58
  • You can use Jackson to map object. Possible Answer here http://stackoverflow.com/questions/6019562/parsing-json-in-spring-mvc-using-jackson-json – Lokesh Nov 18 '14 at 15:00
  • possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – DwB Nov 18 '14 at 15:41
  • Thanks everyone for your replay i have gone through but did not find any appropriate solution. will any one please elaborate here. – Anurag Nov 19 '14 at 06:57
  • Actually i wanna used org.json.simple.JSONArray, org.json.simple.JSONObject, org.json.simple.parser.JSONParser but not org.json one. – Anurag Nov 19 '14 at 06:58

2 Answers2

1

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);
}
jamseernj
  • 1,052
  • 11
  • 17
  • Thanks for reply, is that really compulsion to have a bean class i think without we can achieve. – Anurag Nov 19 '14 at 13:05
0

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;

}

prsmax
  • 223
  • 1
  • 7