简体   繁体   English

使用数字作为属性名称的 Json 映射

[英]Json Mapping With Numbers as Property Names

I have the following json as an example:我以以下 json 为例:

{
    "success": true,
    "data": {
        "1": {
            "amount": "1"
        },
        "2": {
            "amount": "98"
        }
    }
}

Unfortunately, I have no control over the incoming JSON structure.不幸的是,我无法控制传入的 JSON 结构。 I have been trying to find a way to map these to a DTO using JSONProperties, however I can't declare a property using a number.我一直试图找到一种使用 JSONProperties 将这些映射到 DTO 的方法,但是我无法使用数字声明属性。

Also I have tried iterating thought the JSON using JSONObject but I can't seem to get it to go through all child nodes, just the top level.此外,我尝试使用 JSONObject 迭代思考 JSON,但我似乎无法让它通过所有子节点,只是顶级。

JSONObject payload = new JSONObject(jsonString);
JSONObject newPayload = payload;

Iterator<String> keys = payload.keys();

while (keys.hasNext()) {
                String key = keys.next();

                if (StringUtils.isNumber(key)) {
                    newPayload.put("element" + key, payload.get(key));
                    newPayload.remove(key);
                }
}

Has anyone come across a similar situation and found a solution.有没有人遇到过类似的情况并找到了解决办法。

All this to eventually have the JSON transformered into XML... Inherited this platform, no time for refactoring lol, not my choice.所有这一切最终都将 JSON 转换为 XML... 继承了这个平台,没有时间重构 lol,不是我的选择。

There are a number of solutions, but assuming that you need only to deserialize this pathological structure, here's how I'd handle it (Groovy-style for compactness):有许多解决方案,但假设您只需要反序列化这个病理结构,我将如何处理它(Groovy 风格的紧凑性):

class ResponseData {
  Map<String, Long> amounts = new HashMap<>()  // or different key type


  static class WrappedAmount {
    String amount

    Long getAmountAsLong() {
      return Long.valueOf(amount)
    }
  }


  @JsonAnySetter  // this is the magic step
  void appendAmount(String key, WrappedAmount amount) {
    amounts.put(key, amount.getAmountAsLong())
  }
}


class Response {
  boolean success  // REST endpoints should use status codes, not properties
  ResponseData data
}

This will deserialize the response you have into a data structure that's manageable.这会将您的响应反序列化为可管理的数据结构。 If, as you suggested, these keys are indices and will be removed and replaced with something like an ordering of XML tags, you might want to replace HashMap with TreeMap so that you can just iterate over it to produce your output.如果如您所建议的那样,这些键是索引并且将被删除并替换为诸如 XML 标记排序之类的东西,那么您可能希望将HashMap替换为TreeMap以便您可以对其进行迭代以生成输出。

You can use @JsonProperty annotation and specify name.您可以使用@JsonProperty注释并指定名称。

@JsonProperty("1")
private String one;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM