我想在现有的json文件中添加一个键和值对

时间:2017-07-27 12:50:09

标签: java json

我想添加键值对,如

"Signature":64237402i242840805749670 in the existing json field properties

{
"headers":{
    "JMSCorrelationID":"The JMS correlation ID",
    "JMSDeliveryMode":"The JMS delivery mode",

},
"properties":{
    "asu_timestamp":"12345678",
    "asu_type":"Ack",
}

请告诉我如何使用java将其添加到Properties中。

1 个答案:

答案 0 :(得分:0)

package com.sujit;

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;

public class JSONTest {
        public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode nodes = mapper.readValue(new File("D:\\test.json"),ObjectNode.class);
            nodes.with("properties").put("Signature", "64237402i242840805749670 ");
            mapper.writer().writeValue(new File("D:\\test.json"), nodes); // Overwritting the file with new updated JSON data
        }
}

将jar jackson-all-1.9.0 jar文件添加到您的类构建路径中,(链接http://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm

否则,如果您使用的是maven,请添加依赖项

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.0</version>
</dependency>