Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

java - Producing and consuming custom JSON Objects in Spring RESTful services

I have some JSON Objects that are more complex than the JSON representations of the java objects I have. I have methods that build these JSON Objects and I would like to return and consume these directly. I use org.json library to build my JSONs. I could get the GET method working by returning the JSON Object as a String. Is this the correct way to go about it?

@RequestMapping(value = "/getjson", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public String getJson() {
    JSONObject json = new JSONObject();
     JSONObject subJson = new JSONObject();
    subJson .put("key", "value");
    json.put("key", subJson);
    return json.toString();
}

Now I want to know how do I consume a JSON Object? As a string and convert it to a JSON Object?

    @RequestMapping(value = "/post", method = RequestMethod.POST, produces="application/json", consumes="application/json")
    @ResponseBody
    public String post(@RequestBody String json) {
        JSONObject obj = new JSONObject(json);
        //do some things with json, put some header information in json
        return obj.toString();
    }

Is this the correct way to go about my problem? I am a novice, so kindly point out anything that can be done better. Please note: I do not want to return POJOs.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think using jackson library you can do something like below.

@RequestMapping(value = "/getjson", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public String getJson() {
   //your logic
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(json);
}

@RequestMapping(value = "/post", method = RequestMethod.POST, produces="application/json", consumes="application/json")
@ResponseBody
public String post(@RequestBody String json) {
    POJO pj = new POJO();
    ObjectMapper mapper = new ObjectMapper();
    pj = mapper.readValue(json, POJO.class);

    //do some things with json, put some header information in json
    return mapper.writeValueAsString(pj);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...