如何解析扁平化的Json?

时间:2019-03-24 15:04:01

标签: java json

我要求使用扁平化结构JSON,例如在分层Json下:

{
  "employees": [
    {
      "employee1": {
        "employeeId": 123,
        "name": "ABC",
        "type": "permanent",
        "address": {
          "street": "",
          "city": "",
          "zipcode": 123456
        },
        "phoneNumbers": [
          123456,
          987654
        ],
        "designation": "Manager",
        "properties": {
          "age": "29 years",
          "joiningDate": "17-may-2017",
          "salary": "1000 USD"
        }
      }
    },
    {
      "employee2": {
        "employeeId": 123,
        "name": "XYZ",
        "type": "parttime",
        "address": {
          "street": "",
          "city": "",
          "zipcode": 345645
        },
        "phoneNumbers": [
          345332,
          675444
        ],
        "designation": "Contractor",
        "properties": {
          "age": "35 years",
          "joiningatDate": "17-june-2015",
          "salary": "700 USD"
        }
      }
    }
  ]
}

**Could be represented as flat structure Json as below(generated this using json-flattener):**

{
  "employees[0].employee1.address.zipcode": 123456,
  "employees[0].employee1.address.city": "",
  "employees[0].employee1.address.street": "",
  "employees[0].employee1.name": "ABC",
  "employees[0].employee1.employeeId": 123,
  "employees[0].employee1.designation": "Manager",
  "employees[0].employee1.type": "permanent",
  "employees[0].employee1.phoneNumbers[0]": 123456,
  "employees[0].employee1.phoneNumbers[1]": 987654,
  "employees[0].employee1.properties.joiningDate": "17-may-2017",
  "employees[0].employee1.properties.salary": "1000 USD",
  "employees[0].employee1.properties.age": "29 years",
  "employees[1].employee2.address.zipcode": 345645,
  "employees[1].employee2.address.city": "",
  "employees[1].employee2.address.street": "",
  "employees[1].employee2.name": "XYZ",
  "employees[1].employee2.employeeId": 123,
  "employees[1].employee2.designation": "Contractor",
  "employees[1].employee2.type": "parttime",
  "employees[1].employee2.phoneNumbers[0]": 345332,
  "employees[1].employee2.phoneNumbers[1]": 675444,
  "employees[1].employee2.properties.joiningDate": "17-june-2015",
  "employees[1].employee2.properties.salary": "700 USD",
  "employees[1].employee2.properties.age": "35 years"
}

我的问题是,如果我的服务收到上述的扁平化Json,如何将其自动转换为Java域对象,如:

class Employee{
Address address;
Properties property;
} 

是否有任何Java Json解析器支持此自动转换,否则我将必须实现自己的解析逻辑,以根据键中的点来拆分键?

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以看看json-flattener

它可以满足您的需求,甚至更多。

用法很简单:

String json = "{ \"a\" : { \"b\" : 1, \"c\": null, \"d\": [false, true] }, \"e\": \"f\", \"g\":2.3 }";
String jsonStr = JsonFlattener.flatten(json);
System.out.println(jsonStr);
// Output: {"a.b":1,"a.c":null,"a.d[0]":false,"a.d[1]":true,"e":"f","g":2.3}