我有一个由服务器端 C++ 程序生成的 JSON 流,该程序目前正在开发中。我已经获得了生成的 JSON 的示例,我担心我将不得不手动解析 json,我将无法使用 GSON 或 Jackson 等工具提供的普通类映射。
请查看他们提供的以下(有点)人为设计的示例。我关心的部分是具有不同参数的元数据“系列”数组。键 - 例如“键”仅存在于一个数组元素中。这不会导致尝试将此数组映射到特定类的集合时出现问题吗?
最后,我担心“点”对象不相似。我对 JSON 的理解非常有限(作为一个老式的 Java Swing 开发人员),但“点”键值对可能不同的事实是一个问题。
这个 json 流的整个想法是描述一个表,其中包含显示进度的方法,并提供一种从底层硬件请求“更多”的机制。另外,如果您想知道为什么,我正在与瘦客户端(html 浏览器)共享此数据流。
那么我是否正确认为这不会轻易转换为 java 对象?
{
"abort": "abort;session=sessionname",
"data": {
"metadata": [
{
"protocol": "HTTP",
"serie": [
{
"name": "k1",
"description": "xDR ID",
"tooltip": "ASDR Unique Identifier - UiD",
"type": "int64",
"key": "1"
},
{
"name": "c1",
"description": "Answered",
"tooltip": "Request with Response",
"type": "bool"
},
{
"name": "c2",
"description": "Active",
"tooltip": "Session status: active or closed/down",
"type": "bool"
}
]
},
{
"protocol": "DNS",
"serie": [
{
"name": "k1",
"description": "xDR ID",
"tooltip": "ASDR Unique Identifier - UiD",
"type": "int64",
"key": "1"
},
{
"name": "k2",
"description": "Transaction ID",
"type": "int64",
"key": "1",
"display": "number"
},
{
"name": "k3",
"description": "Client",
"tooltip": "Source IP Address",
"type": "string",
"key": "1",
"display": "ip"
}
]
}
],
"summary": [
{
"timestamp": "1331192727",
"protocol": "HTTP",
"activity": "www.google.com",
"results": "OK",
"point": {
"k1": "1",
"c1": "true",
"c2": "true"
}
},
{
"timestamp": "1331192727",
"protocol": "DNS",
"activity": "www.google.com",
"results": "OK",
"point": {
"k1": "1",
"k2": "1.1.4.229"
}
}
]
},
"progress": {
"perc": "100"
},
"more": "13,39,1331192727,1331192760,27236,1.1.4.229,limit=1000,session=sessionname"
}
感谢您提供的任何建议。
-D克洛茨
最佳答案
对于 GSON,假设您要反序列化的类具有 JSON 中出现的所有名称的字段,JSON 中未找到的字段将保留为空:
https://sites.google.com/site/gson/gson-user-guide#TOC-Finer-Points-with-Objects
“反序列化时,JSON 中缺少条目会导致将对象中的相应字段设置为空”
如果 JSON 中允许任意字段名称,事情就会变得有点复杂 - 例如,如果 Point 允许 c1、c2、... cn。但是您可以使用自定义反序列化器来处理这个问题。
https://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer
编辑:
以下是您可以如何为 Point 编写自定义反序列化器:
private class DateTimeDeserializer implements JsonDeserializer<Point> {
public Point deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
List<PointPart> parts = Lists.newArrayList();
for(Map.Entry<String,JsonElement> entry :
json.getAsJsonObject().entrySet()) {
char type = ;
int index = Integer.parseInt(entry.getKey().substring(1)) - 1;
while(parts.size() <= index) {
parts.add(new PointPart());
}
PointPart part = parts.get(index);
switch(entry.getKey().charAt(0)) {
case 'c':
part.c = entry.getValue().getAsBoolean();
break;
case 'k':
part.k = entry.getValue().getAsInt();
break;
}
}
return new Point(parts);
}
}
class Point {
List<PointPart> parts;
Point(List<PointPart> parts) {
this.parts = parts;
}
}
class PointPart {
boolean c;
int k;
}
关于java - JSON 到 Java 对象,建模 json 流的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9844494/