45

Ok, so I've been looking at this for a little while now and am no further on. I've got a Spring MVC servlet that I need to accept JSON from a JavaScript front end web app. To parse the JSON I need to use Jackson. I need to take the values within the JSON and store them into a List in the order they appear in the JSON. I've tried using the JsonFactory with the JsonParser and JsonNode objects but can quite get it to work. I've also tried to just open a BufferedReader and iterate through the request body line by line but again can't quite get this either. I've looked at a couple of related questions on here, but none so far have worked for me.

Could anyone in the know point me in the right direction here please, a web page with an example would be great!

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
MeanwhileInHell
  • 6,780
  • 17
  • 57
  • 106
  • 1
    Using a BufferedReader and iterating line by line is a really bad idea because your code might then be sensitive to changes in the formatting of the json received from the Javascript. Much better to use a real json parser. – Robin Green May 16 '11 at 15:25
  • 1
    please post the code that you've tried and tell us what doesn't work about it (i.e. you expect A but instead you get B), it's far easier to help you out with this info. – matt b May 16 '11 at 15:25

2 Answers2

102

The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).

Define a Java class that resembles the JSON you will be expecting.

e.g. this JSON:

{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : 1
}

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);
}

and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json.

For a full working example see this previous answer of mine.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • This looks exactly like what I'm after, thanks. So I don't think I need to create a new class as the JSON will be very simple like: {"pref1", "pref2"...}, so I was trying to get it added to a List (@RequestBody List body), but this doesn't seem to be getting the following error message, "Can not deserialize instance of java.util.List out of START_OBJECT token". Any ideas? – MeanwhileInHell May 17 '11 at 11:24
  • @NomNomNom I haven't tried that before, guess you'll have to read Jackson docs there. – Sean Patrick Floyd May 17 '11 at 11:30
  • You do not have to create a new class; but structure must match: you can not bind JSON Objects to Java arrays or lists (for obvious reasons). Your JSON has main-level Object with properties (foo, bar, baz), and each property has different kind of value (list, string/boolean, string/number) – StaxMan May 17 '11 at 15:55
  • what does "and you pass in the JSON from above" mean? – zodiac645 Mar 30 '20 at 11:37
  • 1
    @zodiac645 `Fizzle fizzle = new ObjectMapper().readValue(json, Fizzle.class)` – Sean Patrick Floyd Mar 30 '20 at 18:09
  • Actually, my problem is I have a link, an url that contains json data in raw format. I want to send get request to it and display the result in my browser. But, i ve just started to use spring framework and have no idea. Is it possible to do so with it? – zodiac645 Mar 31 '20 at 09:52
  • How can i construct `json` in `readValue(json, Fizzle.class)` from that link? – zodiac645 Mar 31 '20 at 09:53
  • 1
    @zodiac645 there is also the overloaded method [`ObjectMapper.readValue(url, class)`](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html#readValue(java.net.URL,%20java.lang.Class)) but perhaps you should create your own question for this – Sean Patrick Floyd Mar 31 '20 at 14:26
  • I have posted [one](https://stackoverflow.com/questions/60954202/spring-boot-get-request-to-api). Thanks for your help. – zodiac645 Mar 31 '20 at 15:27
  • if we add another property to the class without adding a value for it in the request, would this produce an error ? – HamzaDevXX Mar 13 '23 at 23:04
2

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","my@admin.lan");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

Luffy
  • 1,317
  • 1
  • 19
  • 41
denny
  • 199
  • 1
  • 7