Jackson MismatchedInputException(没有字符串参数构造函数/工厂方法来从字符串值反序列化)

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

我正在使用

SpringBoot 2.3.1-RELEASE
并尝试将 JSON 字符串反序列化为包含对象列表的 POJO,但我不断遇到此错误:

无法构造

com.response.dto.RootDTO
的实例(尽管至少存在一个 Creator):没有字符串参数构造函数/工厂方法来从字符串值('Meta')反序列化 在 [来源:(字符串)""Meta":[{"DimensionName":"版本","DimensionId":"3b4860b9-b215-4192-bd7a-a76f377fc465","DimensionType":"常规","别名": "C0","AttributeId":"211d5-d91f-40ec-9668-20e0da2ae7b3","AttributeName":"版本名称","AttributeKey":"VersionKey"; 行: 1, 列: 1]

这就是我的 JSON 字符串的样子(但在 Eclipse 中带有转义字符):

{"Meta":[{"DimensionName":"版本", "DimensionId":"3b4860b9-b215-4192-bd7a-a76f377fc465, "DimensionType":"常规","别名":"C0","AttributeId" :"211b33d5-d91f-40ec-9668-20e0da2ae7b3","AttributeName":"版本名称","AttributeKey":"VersionKey"}]}.

这是我想要将其反序列化为的类:

@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class RootDTO 
{
  @JsonProperty("Meta")
  private List<MetaDTO> Meta;
}


 @JsonIgnoreProperties(ignoreUnknown = true)
 @Data
 public class MetaDTO 
{

 @JsonProperty("DimensionName")
 private String DimensionName;

 @JsonProperty("AttributeId")
 private String AttributeId;

 @JsonProperty("AttributeName")
 private String AttributeName;

 @JsonProperty("Name")
 private String Name;

 @JsonProperty("Alias")
 private String Alias;
}

这是尝试读取值时崩溃的代码:

 ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        
  objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
         
        objectMapper.readValue(jsonFormattedString, RootDTO.class));
         

我仅在运行时看到此问题

Junit
(版本:4.12)。我在堆栈跟踪中看到
jackson-databind-2.11.0
spring-test-5.2.7.RELEASE
。但是,我使用浏览器或邮递员的调用进行调试,它工作正常。我不确定当我将它指定为列表时它为什么要查找字符串 Meta。什么可能导致此问题?有什么建议吗?

编辑:事实证明,提供给

ObjectMapper
的字符串不是正确的。有这行代码
 String jsonFormattedString = responseEntity.getBody().substring(1,        responseEntity.getBody().lastIndexOf("\"")).replaceAll("\\\\", "");
这使得我的模拟字符串无效。我需要弄清楚我们为什么要这样做。

java json spring-boot jackson objectmapper
1个回答
0
投票

将变量的第一个字母更改为小写。并删除 JsonProperty。

如下。并自动生成 setter 和 getter。

私有字符串维度名称;

 private String attributeId;
 private String attributeName;
 private String name;

 public void setName(String name){
       this.name=name;
 }
 .........
 .........
 //All setter getter

添加

@JsonGetter("Meta")
每个 getter 方法。

例如如下。

@JsonGetter("Meta")
public List<Meta> getMeta(){

return meta;

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