java - 如何将已解析 JSON 的 Java 列表解析为大 JSON?
问题描述
我习惯Jackson
了serialize/deserialize
JSON
。
我有一个List<String>
里面的所有元素都已经格式化serialized
的。JSON
我想从中产生一个大JSON
的List
。
换句话说,我有:
List<String> a = new ArrayList<>();
a[0] = JSON_0
a[1] = JSON_1
...
a[N] = JSON_N
我想渲染:
[
{JSON_0},
{JSON_1},
...
{JSON_N}
]
这样做的最佳方法是什么Jackson
?
解决方案
可能更简单的解决方案是创建ArrayNode
和使用addRawValue方法:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.util.RawValue;
public class JsonApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
ArrayNode nodes = mapper.getNodeFactory().arrayNode();
nodes.addRawValue(new RawValue("{}"));
nodes.addRawValue(new RawValue("true"));
nodes.addRawValue(new RawValue("{\"id\":1}"));
System.out.println(mapper.writeValueAsString(nodes));
}
}
上面的代码打印:
[{},true,{"id":1}]
您还可以创建一个POJO
带有列表并使用@JsonRawValue
注释。但是如果你不能有额外的根对象,你需要为它实现自定义序列化器。POJO
带有自定义序列化程序的示例:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
List<String> jsons = new ArrayList<>();
jsons.add("{}");
jsons.add("true");
jsons.add("{\"id\":1}");
RawJsons root = new RawJsons();
root.setJsons(jsons);
System.out.println(mapper.writeValueAsString(root));
}
}
@JsonSerialize(using = RawJsonSerializer.class)
class RawJsons {
private List<String> jsons;
public List<String> getJsons() {
return jsons;
}
public void setJsons(List<String> jsons) {
this.jsons = jsons;
}
}
class RawJsonSerializer extends JsonSerializer<RawJsons> {
@Override
public void serialize(RawJsons value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartArray();
if (value != null && value.getJsons() != null) {
for (String json : value.getJsons()) {
gen.writeRawValue(json);
}
}
gen.writeEndArray();
}
}
如果您需要为SerializationFeature.INDENT_OUTPUT
数组中的所有项目启用功能,则需要反序列化所有内部对象并再次序列化它们。
也可以看看:
推荐阅读
- r - 在 ggplot 中使用 plotmath 表达式的两行注释
- php - Codeigniter where 和 where db 使用数组查询
- r - How to set the fontsize of a table footnote
- javascript - Angular, set dynamic style to button (hover)
- android - 如何访问 RecyclerView 位置
- rust - How to get the local time zone name in Rust?
- mule - creating an XML attribute from var in dataweave 2.0
- java - input arabic characters with scanner in maven project
- c++ - Why does this very simple and little C++ program terminates with -1073741819 (0xC0000005)?
- python - print all topic in the print version