从JSON数组反序列化JSON

huangapple go评论75阅读模式
英文:

Deserialize JSON from a JSON array

问题

{
"Warnings": [
{
"Message": "账户代码 '48s9' 已被删除,因为它不匹配已识别的账户"
},
{
"Message": "账户代码 '48s9' 已被删除,因为它不匹配已识别的账户"
}
]
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class WarningsClass {

private String Message;

public String getMessage() {
return Message;
}

public void setMessage(String message) {
Message = message;
}

}

英文:

I am using Jackson and I am trying to deserialize a JSON response that looks like the following:

{
	"Warnings": [{
			"Message": "Account code '48s9' has been removed as it does not match a recognised account"
		},
		{
			"Message": "Account code '48s9' has been removed as it does not match a recognised account"
		}
	]
}

am I correct in saying that the class would look as follows? Is there some way this can be done?

@JsonIgnoreProperties(ignoreUnknown = true)
public class WarningsClass {

  private String Message;

  public String getMessage() {
    return Message;
  }

  public void setMessage(String message) {
    Message = message;
  }

}

答案1

得分: 1

// 成功找到解决方法:

// 导入 com.fasterxml.jackson.databind.ObjectMapper; // 版本 2.11.1
// 导入 com.fasterxml.jackson.annotation.JsonProperty; // 版本 2.11.1
/* ObjectMapper om = new ObjectMapper();
Root root = om.readValue(myJsonString), Root.class); */
public class Warning{
    @JsonProperty("Message") 
    public String message;
}

public class WarningsClass{
    @JsonProperty("Warnings") 
    public List<Warning> warnings;
}

WarningsClass messageResponse = mapper.readValue(data, WarningsClass.class);

类似这样的代码将起作用
英文:

was able to figure it out:

// import com.fasterxml.jackson.databind.ObjectMapper; // version 2.11.1
// import com.fasterxml.jackson.annotation.JsonProperty; // version 2.11.1
/* ObjectMapper om = new ObjectMapper();
Root root = om.readValue(myJsonString), Root.class); */
public class Warning{
    @JsonProperty(&quot;Message&quot;) 
    public String message;
}

public class WarningsClass{
    @JsonProperty(&quot;Warnings&quot;) 
    public List&lt;Warning&gt; warnings;
}


WarningsClass messageResponse = mapper.readValue(data, WarningsClass.class);

something like this would work

huangapple
  • 本文由 发表于 2020年8月6日 15:54:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63279145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定