简体   繁体   English

将 json 反序列化为列表<object><div id="text_translate"><p>我有 json:</p><pre> "taxLevels": [{ "code": "VAT", "percentage": 19.0 } ]</pre><p> 这确实是List&lt;TTaxLevel&gt;</p><p> 我有<strong>Model.class</strong> :</p><pre> public class Model{ private final List&lt;TTaxLevel&gt; taxLevels; }</pre><p> 和<strong>TtaxLevel.class</strong> :</p><pre> @NoArgsConstructor public class TTaxLevel { private String code; private Double percentage; }</pre><p> 但我在这里收到错误:</p><blockquote><p> [Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of java.util.LinkedHashMap&lt;java.lang.String,java.lang.String&gt; out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.LinkedHashMap&lt;java.lang.String,java.lang.String&gt; out of START_ARRAY token at [Source: (PushbackInputStream); 行:36,列:19](通过参考链:...Model["taxLevels"])]]</p></blockquote><p> 我可以以某种方式强制jackson在这里ArrayList而不是Map吗? 这是一个问题。</p><p> 这是反序列化代码:</p><pre> Model model = new ObjectMapper().readValue(content, Model.class);</pre></div></object>

[英]Deserializing json as List<Object>

I have json:我有 json:

"taxLevels": [{
        "code": "VAT",
        "percentage": 19.0
    }
]

This is truly List<TTaxLevel>这确实是List<TTaxLevel>

I have Model.class :我有Model.class

public class Model{

    private final List<TTaxLevel> taxLevels;
}

And TTaxLevel.class :TtaxLevel.class

@NoArgsConstructor
public class TTaxLevel {

    private String code;
    private Double percentage;
}

But I receive error here:但我在这里收到错误:

[Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of java.util.LinkedHashMap<java.lang.String,java.lang.String> out of START_ARRAY token; [Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of java.util.LinkedHashMap<java.lang.String,java.lang.String> out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.LinkedHashMap<java.lang.String,java.lang.String> out of START_ARRAY token at [Source: (PushbackInputStream); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.LinkedHashMap<java.lang.String,java.lang.String> out of START_ARRAY token at [Source: (PushbackInputStream); line: 36, column: 19] (through reference chain: ...Model["taxLevels"])]]行:36,列:19](通过参考链:...Model["taxLevels"])]]

Can I force somehow jackson to expect type here ArrayList instead of Map ?我可以以某种方式强制jackson在这里ArrayList而不是Map吗? This is an issue.这是一个问题。

This is deserialization code:这是反序列化代码:

 Model model =  new ObjectMapper().readValue(content, Model .class);  

Please add getter/setter methods to you classes and provide no-arg constructor.请为您的类添加 getter/setter 方法并提供无参数构造函数。 Also you json is not completely valid, it should be:另外你 json 不完全有效,应该是:

{
  "taxLevels": [
    {
      "code": "VAT",
      "percentage": 19.0
    }
  ]
}

I trided putting it inside resource folder, fetch and then response to a sample request.我尝试将它放在资源文件夹中,获取然后响应示例请求。 Here is the sample code:这是示例代码:

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
class Model {
    private List<TTaxLevel> taxLevels;
}

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
class TTaxLevel {
    private String code;
    private Double percentage;
}

@RequestMapping("tax-level")
@RestController
class SampleRequestBody {
    private final ObjectMapper objectMapper;

    SampleRequestBody(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @PostMapping
    public Map<String, Model> taxLevel(@RequestBody Model model) throws JsonProcessingException {
        final Map<String, Model> response = new HashMap<>(1);
        response.put("data",  model);
        return response;
    }

    @GetMapping
    public Model getTaxLevel() throws IOException {
        InputStream inputStream = new ClassPathResource("tax-level.json").getInputStream();
        return objectMapper.readValue(inputStream, Model.class);
    }
}

So there are two issues:所以有两个问题:

  1. You need to provide getters and setters for your classes since the fields are all private;您需要为您的类提供 getter 和 setter,因为这些字段都是私有的;
  2. You need to change the Json to include "{" at the beginning and "}" at the end.您需要将 Json 更改为在开头包含“{”,在结尾包含“}”。
    {
        "taxLevels": [{
                "code": "VAT",
                "percentage": 19.0
            }
        ]
    }

列表<object> null 在 Spring 启动 Z594C103F2C6E04C3D8AB059F031E0C1 中反序列化 json 时<div id="text_translate"><p>我在 Spring 引导应用程序中遇到了 controller 问题。 当我在 controller(URI/调用)上进行调用时,object 列表始终是 null。</p><pre> { "code": "TEST", "name": "TEST NAME", "groupe": "A1", "list": [ {"type":"web", "link":"https://google.com/"}, {"type":"web", "link":"https://google2.com/"} ] }</pre><pre class="lang-java prettyprint-override"> @PostMapping(value="/call") public ResponseEntity&lt;Void&gt; ajouterEnvironnement(@RequestBody First first) { first.getCode() // value: "TEST" first.getList() // value: null }</pre><pre class="lang-java prettyprint-override"> public class First { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String code; private String name; private String groupe; @OneToMany(mappedBy = "first", cascade = CascadeType.ALL, fetch = FetchType.EAGER) private List&lt;Second&gt; list; }</pre><pre class="lang-java prettyprint-override"> public class Second { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String type; private String link; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "first_id", nullable = false) private First first; }</pre></div></object> - List<object> null when deserializing json in Spring Boot controller

错误的反序列化列表<object>与 gson<div id="text_translate"><p> 我用List&lt;Object&gt;调试CUSTOMER object:</p><p> <a href="https://i.stack.imgur.com/Gh2Mx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gh2Mx.png" alt="在此处输入图像描述"></a></p><p> 这是 CUSTOMER.class:</p><pre> public class CUSTOMER { @XmlElements({ @XmlElement(name = "ADDRESS", type = ADDRESS.class), @XmlElement(name = "ZIP", type = ZIP.class), @XmlElement(name = "CITY", type = CITY.class), @XmlElement(name = "COUNTRY", type = COUNTRY.class), }) protected List&lt;Object&gt; addressAndZIPAndCITY; // other fields }</pre><p> 但是当我反序列化并从中创建 json 时,它仅包含:</p><pre> { "addressAndZIPAndCITY": [ { "value": "some value", "type": "some type" }, { "value": "some value 2", "type": "some type 2" }] }</pre><p> 缺少 ADRESS、ZIP、CITY 和 COUNTRY 对象标题。 所以反序列化不好。</p><p> 我无法更改List&lt;Object&gt;声明。 是否可以选择将其反序列化为带有 ADRESS、ZIP、CITY 等的 json? 像这样:</p><pre> { "addressAndZIPAndCITY": [{ "ADDRESS": { "value": "some value", "type": "some type" } }, { "ZIP": { "value": "some value 2", "type": "some type 2" } } ] }</pre><p> 编辑:我的意思是它看起来像 GSON 不知道哪个 object 在那里,但可能你知道如何向 model 添加一些注释或其他东西来识别它?</p></div></object> - Wrong deserializing List<Object> with gson

暂无
暂无

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

相关问题 使用列表属性将JSON反序列化为Object - Deserializing JSON into Object with list attribute 反序列化以对象ID作为对象名称的JSON对象列表 - Deserializing a list of JSON objects having object's ID as an object name 反序列化JSON对象 - Deserializing JSON object 使用列表反序列化JSON包装器对象将返回null属性 - Deserializing JSON wrapper object with list returns null properties 列表<object> null 在 Spring 启动 Z594C103F2C6E04C3D8AB059F031E0C1 中反序列化 json 时<div id="text_translate"><p>我在 Spring 引导应用程序中遇到了 controller 问题。 当我在 controller(URI/调用)上进行调用时,object 列表始终是 null。</p><pre> { "code": "TEST", "name": "TEST NAME", "groupe": "A1", "list": [ {"type":"web", "link":"https://google.com/"}, {"type":"web", "link":"https://google2.com/"} ] }</pre><pre class="lang-java prettyprint-override"> @PostMapping(value="/call") public ResponseEntity&lt;Void&gt; ajouterEnvironnement(@RequestBody First first) { first.getCode() // value: "TEST" first.getList() // value: null }</pre><pre class="lang-java prettyprint-override"> public class First { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String code; private String name; private String groupe; @OneToMany(mappedBy = "first", cascade = CascadeType.ALL, fetch = FetchType.EAGER) private List&lt;Second&gt; list; }</pre><pre class="lang-java prettyprint-override"> public class Second { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String type; private String link; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "first_id", nullable = false) private First first; }</pre></div></object> - List<object> null when deserializing json in Spring Boot controller 使用LocalDateTime字段将JSON反序列化为对象 - Deserializing JSON to Object with LocalDateTime field 用杰克逊反序列化嵌套的json对象 - Deserializing nested json object with Jackson 将多态 Json object 反序列化为 POJO - Deserializing a polymorphic Json object to a POJO 基于对象类型反序列化JSON - Deserializing JSON based on object type 错误的反序列化列表<object>与 gson<div id="text_translate"><p> 我用List&lt;Object&gt;调试CUSTOMER object:</p><p> <a href="https://i.stack.imgur.com/Gh2Mx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gh2Mx.png" alt="在此处输入图像描述"></a></p><p> 这是 CUSTOMER.class:</p><pre> public class CUSTOMER { @XmlElements({ @XmlElement(name = "ADDRESS", type = ADDRESS.class), @XmlElement(name = "ZIP", type = ZIP.class), @XmlElement(name = "CITY", type = CITY.class), @XmlElement(name = "COUNTRY", type = COUNTRY.class), }) protected List&lt;Object&gt; addressAndZIPAndCITY; // other fields }</pre><p> 但是当我反序列化并从中创建 json 时,它仅包含:</p><pre> { "addressAndZIPAndCITY": [ { "value": "some value", "type": "some type" }, { "value": "some value 2", "type": "some type 2" }] }</pre><p> 缺少 ADRESS、ZIP、CITY 和 COUNTRY 对象标题。 所以反序列化不好。</p><p> 我无法更改List&lt;Object&gt;声明。 是否可以选择将其反序列化为带有 ADRESS、ZIP、CITY 等的 json? 像这样:</p><pre> { "addressAndZIPAndCITY": [{ "ADDRESS": { "value": "some value", "type": "some type" } }, { "ZIP": { "value": "some value 2", "type": "some type 2" } } ] }</pre><p> 编辑:我的意思是它看起来像 GSON 不知道哪个 object 在那里,但可能你知道如何向 model 添加一些注释或其他东西来识别它?</p></div></object> - Wrong deserializing List<Object> with gson
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM