0

I have faced problem, while mapping my object to JSON.

I have an object, which I need to convert to propper JSON, but some of my object's String fields are already in JSON format:

Sdr sdr = new Sdr();
sdr.setLocation_area(("location_area"));
sdr.setEvent_info(("{\"chargeableDur\":0}"));
sdr.setAgent_info("{\"scp\":\"NAVI\",\"stack\":\"CAP2\"}");
sdr.setService_info(("{\"bcap\":\"8090A3\",\"balID\":55969859}"));
sdr.setStarttime(("starttime"));

For JSON mapping I am using ObjectMapper:

public String toJsonString() {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(this);
    } catch (JsonProcessingException e) {
        logger.error(e.getMessage());
    }
    return toString();
}

However, ObjectMapper fails to map Strings, that already contains JSON correctly, and after mapping I get this type of JSON:

{  
   "event_info":""{\"chargeableDur\":0}",
   "location_area":"location_area",
   "agent_info":"{\"scp\":\"NAVI\",\"stack\":\"CAP2\"}",
   "service_info":""{\"bcap\":\"8090A3\",\"balID\":55969859}",
   "starttime":"starttime"
}

I want ObjectMapper to map my object like that:

{  
   "event_info":{  
      "chargeableDur":0
   },
   "location_area":"location_area",
   "agent_info":{  
      "scp":"NAVI",
      "stack":"CAP2"
   },
   "service_info":{  
      "bcap":"8090A3",
      "balID":55969859
   },
   "starttime":"starttime"
}
4
  • So you want to JSONify the strings, and let the already JSON'ed as they are? Is there any way to know which one are already json'ed? Commented Aug 2, 2017 at 14:14
  • mapper.writeValueAsString(this); uses the getX() method of each attributes of your class to put them in a JSon ? If so, just re-define those methods to return them w/o the JSon format when they have one. Commented Aug 2, 2017 at 14:15
  • what if you change those strings to be their byte array implementation, and have the deserialize turn them back to strings Commented Aug 2, 2017 at 14:17
  • There is only 3 fields which is already JSON'ed : event_info, agent_info and service_info, but I don't know how to tell object manager, that these fields are already JSON'ed Commented Aug 2, 2017 at 14:18

1 Answer 1

0

Seems that your json result is stringified. Try to put the string result in separate JSONObject as

return new JSONObject(mapper.writeValueAsString(this)).toString();
Sign up to request clarification or add additional context in comments.

Comments

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.