JSON到Java Objects,用于建模json流的最佳实践 [英] JSON to Java Objects, best practice for modeling the json stream

查看:133
本文介绍了JSON到Java Objects,用于建模json流的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON流由当前正在开发的服务器端C ++程序生成。我已经得到了一个结果JSON的样本,我担心我将不得不手工解析json,我将无法使用GSON或Jackson等工具提供的普通类映射。

I have a JSON stream being generated by a server side C++ program that is currently in development. I've been given a sample of the resulting JSON and I am concerned that I will have to parse the json by hand, that I won't be able to use normal class mapping provided by tools such as GSON or Jackson.

请看一下他们提供的以下(有些)人为的例子。我关注的部分是具有不同参数的元数据serie数组。键 - 键例如仅存在于一个数组元素中。这不会导致尝试将此数组映射到特定类的集合时出现问题吗?

Please take a look at the following (somewhat) contrived example they have provided. The sections I'm concerned with are the meta data "serie" array having different parameters. The key - "key" for example is present in only one of the array elements. Will this not cause issues trying to map this array to a collection of a specific class?

最后,我担心点对象不相似。我对JSON(作为一个老式的java swing开发人员)的理解非常有限,但点键值对可以不同的事实 - 是一个问题。

Lastly, I am concerned that the "point" object is not similar. I have very limited understanding of JSON (being an old fashioned java swing developer) but the fact that the "point" key value pairs can be different - is a problem.

这个json流的整个想法是描述一个表,显示进度的方法,并提供一种从底层硬件中寻求更多的机制。此外,如果你想知道为什么,我正在与瘦客户端(HTML浏览器)共享这个数据流。

The whole idea for this json stream is to describe a table, with ways of showing progress and to provide a mechanism for asking for "more" from the underlying hardware. Also if you are wondering why, I am sharing this datastream with a thin client (html browser).

所以我更正,这不会轻易转换为java对象?

So am I correct that this will not easily convert to java objects?

{
  "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 Klotz

推荐答案

使用GSON,假设您要反序列化的类具有JSON中出现的所有名称的字段,那么JSON中找不到的字段将只是left null:

With GSON, assuming that the class you are deserializing into has fields for all the names that appear in the JSON, the fields not found in the JSON will just be left null:

https://sites.google.com/site/gson/gson-user-guide#TOC-Finer-Points-with-Objects

在反序列化时,JSON中缺少一个条目会导致将对象中的相应字段设置为null

"While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null"

如果JSON中允许任意字段名称,事情会变得复杂一些 - 例如,如果Point允许c1,c2,... cn。但您可以使用自定义反序列化程序处理此问题。

Things get a little more complicated if arbitrary field names are allowed in the JSON - for example, if Point allows c1, c2, ... cn. But you can handle this with a custom deserializer.

https://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer

编辑:

以下是为Point编写自定义反序列化器的方法:

Here's how you might write a custom deserializer for 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;
}

这篇关于JSON到Java Objects,用于建模json流的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆