【问题标题】:Convert json with key dynamic to POJO.. java spring boot将带有密钥动态的json转换为POJO .. java spring boot
【发布时间】:2020-05-21 16:34:25
【问题描述】:

我需要将 json 转换为 pojo 我已经有使用它的服务但我想把它带到一个 POJO 以便能够处理它

这都是 Json:

{
"meta": {
"status": "success",
"version": "2.0"
},
"data": {
"id": "M!t!Ch!v1!0000100002-5gda5bq0059b1-1245432868",
"token": "d71b160d82dfeeca87aa580f526d8570",
"privileges": {
  "__GLOBAL__": {
    "Store": {
      "1-m!i!s-045-158": {
        "*": -1
      },
      "1-m!i!s-047-324": {
        "*": -1
      },
      "1-m!i!s-031-1491": {
        "*": -1
      },
      "1-m!i!s-046-2": {
        "*": -1
      }
    }
  }
 },
"data": {
   "accessorId": 100001
 }
 }
 }

这部分所有的键都是动态的:

"1-m!i!s-045-158":{"*":-1} // **the key: 1-m!i!s-045-158 is dinamic** 
{"1-m!i!s-045-158":{"*":-1},"1-m!i!s-047-324":{"*":-1},"1-m!i!s-031-1491":{"*":-1},"1-m!i!s-046-2":{"*":-1}}

这是我的控制器

    public JsonNode Evento(JsonNode json) {


    HttpHeaders header = new HttpHeaders();
    //header.add("Content-Type", "application/json");
    RestTemplate template = new RestTemplate();
    JsonNode node = mapper.convertValue(json  , JsonNode.class);
    HttpEntity<?> request = new HttpEntity<>(node);
    JsonNode resultado = template.postForObject("http://localhost:8083/moddo-channels/api/miinto", request, JsonNode.class);


    System.out.println(json.findPath("stote"));
    System.out.println(resultado);

    return json;

}

【问题讨论】:

    标签: java json spring-boot


    【解决方案1】:

    你必须用所有字段写POJO,

    private Meta meta;
    

    public class Meta{
       private String status;
       private String version;
    }
    

    等这种风格,问题可能出在商店 - 它必须是地图

    在此之后,您可以使用 Jackson ObjectMapper 并从您的响应中读取对象

    【讨论】:

    • 是的,我知道我可以从其他 json 制作 POJO,但这有动态密钥。我对这部分感到困惑。
    • 好,Store 是 HashMap where class CustomObject{ @JsonProperties("*") private int star;}
    猜你喜欢
    • 2021-01-24
    • 2020-01-29
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 2020-04-27
    • 2019-06-25
    相关资源
    最近更新 更多