usman
usman

Reputation: 1391

How to treat JSON Value as String Object in Java using ObjectMapper?

I am facing issue when converting Json to Java Object. My "jsonText" field have json as value which i want to be placed in String. My custom Class hass following structure.

Class Custom{
    @JsonProperty(value = "field1")
    private String field1;
    @JsonProperty(value = "jsonText")
    private String jsonText;
}

Below is my code:

ObjectMapper mapper = new ObjectMapper();

JsonNode node = mapper.readTree(inputString);
String nodeTree = node.path("jsonText").toString();
List<PatientMeasure> measuresList =mapper.readValue(nodeTree,
                            TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, CustomClass.class) );

Json to convert is :

    "field1" : "000000000E",                
    "jsonText" : {
        "rank" : "17",
        "status" : "",
        "id" : 0
    }

Exception got:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.StringReader@3362f02f; line: 1, column: 108] (through reference chain: com.Custom["jsonText"])

Upvotes: 0

Views: 3872

Answers (2)

Franjavi
Franjavi

Reputation: 657

You can use a custom deserializer like this:

public class AnythingToString extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        TreeNode tree = jp.getCodec().readTree(jp);
        return tree.toString();
    }
}

And then annotate your field to use this deserializer:

class Custom{
    @JsonProperty(value = "field1")
    private String field1;
    @JsonProperty(value = "jsonText")
    @JsonDeserialize(using = AnythingToString.class)
    private String jsonText;
}

Upvotes: 1

Paras Nakum
Paras Nakum

Reputation: 230

You can try this:

JSONArray ar= new JSONArray(result);
JSONObject jsonObj= ar.getJSONObject(0);
String strname = jsonObj.getString("NeededString");

Upvotes: 1

Related Questions