k_b
k_b

Reputation: 343

Coverting JSON String which is part of JSON object to JSON Object on the run

I am consuming a REST web services using REST template in my project which returns a JSON as below:

{"data": [{
        "id": "INT-1468819244684-event-no-97",
        "object1": {
            "JSONString": "{\"object2\":[{\"object3\":\"value3\",\"object4\":\"value4\"}]}"
        }
    }]

}

While consuming the above JSON response I am able to create a bean class and able to dump JSON object/values into the same.

But the problem is above json response contains a string as below:

"JSONString": "{\"object2\":[{\"object3\":\"value3\",\"object4\":\"value4\"}]}"

which is actually a json. So I have a bean in which I can fetch JSONString as String. So currently I can use below bean structure to fetch response in objects:

public class response {
Data data;
}

public class Data {
String id;
Object1 object1;
}

public class Object1 {
String jsonString;
}

But above jsonString contains a string in the form of json, so I want to somehow convert this JSON String to JSON Object at run time only when other objects are created and dump all its content in the same bean so that application should be ready to use its content. So ideally my bean hierarchy should be something like below:

public class response {
Data data;
}

public class Data {
String id;
Object1 object1;
}


public class Object1 {
JSONString jsonString;
}

public class JSONString {
Object2 object2;
}

public class Object2 {
String object3;
String object4;
}

Please guide me how to do the same.

Upvotes: 2

Views: 116

Answers (1)

Rick Chen
Rick Chen

Reputation: 181

You can use Jackson's ObjectMapper.readValue in this way:

// Create or use your existing ObjectMapper
ObjectMapper om = new ObjectMapper();

@JsonProperty("JSONString")
public String getJSONString() {
    if (this.jsonString == null)
        return null;
    return om.writeValueAsString(this.jsonString);
}

public void setJSONString(String s) {
    this.jsonString = om.readValue(s, JSONString.class);
}

Upvotes: 3

Related Questions