0

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"])

2 Answers 2

1

You can try this:

JSONArray ar= new JSONArray(result);
JSONObject jsonObj= ar.getJSONObject(0);
String strname = jsonObj.getString("NeededString");
Sign up to request clarification or add additional context in comments.

2 Comments

i need to map it directly on String object. is there any Json Property
you can't directly get the value into a string and you can get the value using JSON object with string title name as you given above....
1

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

1 Comment

During serialization, won't it simply escape the quotes and brackets?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.