带有Java POJO空格的JSON密钥

问题描述 投票:0回答:1

我有以下JSON,问题是Win the match标签,因为空格:

{
    "api": {
        "results": 10,
        "odds": {
            "Win the match": {
                "1": {
                    "label": "1",
                    "pos": "1",
                    "odd": "1.51"
                },
                "2": {
                    "label": "2",
                    "pos": "3",
                    "odd": "4.90"
                },
                "N": {
                    "label": "N",
                    "pos": "2",
                    "odd": "3.05"
                }
            }
        }
    }
}

在我的一个Java Class POJO

import com.fasterxml.jackson.annotation.JsonProperty;

public class OddsClass {

    private The1_N22_EMT winTheMatch;

    @JsonProperty("Win the match")
    public The1_N22_EMT getWinTheMatch() { return winTheMatch; }
    @JsonProperty("Win the match")
    public void setWinTheMatch(The1_N22_EMT value) { this.winTheMatch = value; }

}

问题是此属性未正确映射。请,我需要你的帮助才能做出正确的映射。

java json jackson pojo
1个回答
0
投票

编辑

JSON payload比你想象的要简单。对于动态键,请使用Map。在你的情况下,你在MapMap,因为你有两个级别的动态键。有时从POJO生成的JSON非常复杂。你应该从POJO生成JSON Schema模型。您的模型可能如下所示:

class ApiWrapper {

    private Api api;

    // getters, setters, toString
}

class Api {

    private int results;
    private Map<String, Map<String, Match>> odds;

    // getters, setters, toString
}

class Match {

    private String label;
    private String pos;
    private String odd;

    // getters, setters, toString
}

在编辑之前

你有两个棘手的案例:

  • 带空格的键 - 需要使用JsonProperty注释。
  • 具有动态键的对象 - 应该映射到Map<String, ?>

POJO模型的简单示例:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();

        ApiWrapper api = mapper.readValue(jsonFile, ApiWrapper.class);

        System.out.println(api);
    }
}

class ApiWrapper {

    private Api api;

    // getters, setters, toString
}

class Api {

    private int results;
    private Odds odds;

    // getters, setters, toString
}

class Odds {

    @JsonProperty("Win the match")
    private Map<String, Match> winTheMatch;

    // getters, setters, toString
}

class Match {

    private String label;
    private String pos;
    private String odd;

    // getters, setters, toString
}

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.