在下面的代码中,我正在替换" con"标记值与新声明的字符串" con"值(的" {\" payload_dl \":{\" deveui \":\" 23456 \"}}&# 34; )。但是这样做时,值将存储为普通字符串而不包含转义字符。
如何在jsonNode中替换时转义字符串值。
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jayway.jsonpath.JsonPath;
ObjectMapper mapper = new ObjectMapper();
JsonFactory jsonFactory = new JsonFactory();
JsonParser jp = jsonFactory.createJsonParser({"m2m:cin":{"con":"{\"payload_dl\":{\"deveui\":\"765348\"}});
jp.setCodec(new ObjectMapper());
JsonNode jsonNode = jp.readValueAsTree();
String con = "{\"payload_dl\":{\"deveui\":\"23456\"}}";
changePayloadContent(jsonNode, "con", con);
logger.info("Modified Payload content ::: "+ jsonNode);
return mapper.writeValueAsString(jsonNode);
changePayloadContent方法,
public static void changePayloadContent(JsonNode parent, String fieldName, String newValue) throws JsonProcessingException, IOException {
logger.debug("Start of change");
ObjectMapper mapper = new ObjectMapper();
if (parent.has(fieldName)) {
try {
JsonNode jsonNode = mapper.readTree(newValue);
((ObjectNode) parent).put(fieldName, jsonNode);
} catch (Exception e) {
logger.info("GenericFlow::replace::NewValue is not JSON String");
((ObjectNode) parent).put(fieldName, newValue);
}
}
for (JsonNode child : parent) {
changePayloadContent(child, fieldName, newValue);
}
logger.debug("End of change");
}