0

在下面的代码中,我将“con”标记值替换为新声明的字符串“con”值(“{\”payload_dl\”:{\“deveui\”:\“23456\”}}“)。但是这样做时,该值将存储为没有转义字符的普通字符串。

如何在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");
    }
4

0 回答 0