如何将值附加到现有的 json 数组?
我现有的 json 数组具有以下值
{
"test": [
1,
2,
3,
4
]
}
我想将“0”添加到 json 数组中,以便新的 json 数组看起来像
{
"test": [
0,
1,
2,
3,
4
]
}
最佳答案
使用 Java 和 Jackson 库,您可以将 (json) 字符串反序列化为 Java 对象,添加条目,然后序列化修改后的对象(将其打印为 Json 格式)。
例如,使用此代码
package json;
import java.util.Collections;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class UseJson {
public static void main(String[] args) throws Exception {
ObjectMapper om = new ObjectMapper();
String json = "{\r\n" +
" \"test\": [\r\n" +
" 1,\r\n" +
" 2,\r\n" +
" 3,\r\n" +
" 4\r\n" +
" ]\r\n" +
"} ";
System.out.println("json="+json);
Wrap val = om.readValue( json, Wrap.class);
System.out.println("read val="+val);
val.test.add(0);
Collections.sort(val.test);
System.out.println("val="+val);
om.enable(SerializationFeature.INDENT_OUTPUT);
String json2 = om.writeValueAsString(val);
System.out.println("json2="+json2);
}
}
class Wrap {
public List<Integer> test;
@Override
public String toString() {
return "Wrap[test=" + test + "]";
}
}
你得到..
json={
"test": [
1,
2,
3,
4
]
}
read val=Wrap[test=[1, 2, 3, 4]]
val=Wrap[test=[0, 1, 2, 3, 4]]
json2={
"test" : [ 0, 1, 2, 3, 4 ]
}
(将在 Maven 项目中编译,包括 jackson-core
和 jackson-databind
)
关于Java json 将值附加到 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54634786/