我想补充现有JSON文件
问题描述:
一个键值对我想要添加的键值对像我想补充现有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将其添加到属性。
答
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 杰克逊全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>
您的新键值是否来自任何来源,并且您想将其添加到现有的JSON中?还有一个,你想添加特定的标签(如标题,属性)或任何地方? – sForSujit
我正在通过使用java代码生成键值,我想将它添加到现有的JSON属性标签 – UtkarshaG
好吧,给我一些时间,我会给你解决方案 – sForSujit