鉴于以下json
customer_id av.delay_30days av.delay_30_days_TYPE_A av.delay_30_days_TYPE_B
A 8 4 15
我想忽略“国家”而取代国家的价值。因此,在映射后我的json应该看起来如此
{
"countries":{
"country":[{
"name":"USA",
"independence":"July 4, 1776",
}],
},
}
目前ObjectMapper可以使用吗?
编辑:下面是Pojo
{
"countries": [{
"name":"USA",
"independence":"July 4, 1776",
}],
}
我正在做这个
public class Result {
private static final long serialVersionUID = 6403654749443599206L;
@Getter @Setter @JsonProperty("country") private List<Country> countries;
}
public class Country {
private static final long serialVersionUID = 6403654749443599206L;
@Getter @Setter private String name;
@Getter @Setter private String independence;
}
答案 0 :(得分:0)
输入json的语法错误。它应该是这样的
{
"countries":{
"country":[{
"name":"USA",
"independence":"July 4, 1776"
}]
}
}
ObjectMapper用于将json转换为Object和Object为json。无论如何,要将第一个json转换为另一个你想要的东西,你可以做这样的事情:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.IOException;
import java.util.List;
public class ConvertExample {
public static void main(String[]args) {
String inputJson = new String("{\"countries\":{\"country\":[{\"name\":\"USA\", \"independence\":\"July 4, 1776\"}]}}");
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT); //To indent output, optional
try {
StartPojo startPojo = mapper.readValue(inputJson, StartPojo.class);
EndPojo endPojo = new EndPojo();
endPojo.countries = startPojo.getCountries().getCountry();
String outputJson = mapper.writeValueAsString(endPojo);
System.out.println("Output:");
System.out.println(outputJson);
} catch (IOException e) {
e.printStackTrace(); //Cannot read the input json
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class StartPojo {
private Countries countries;
public Countries getCountries() {
return countries;
}
public void setCountries(Countries countries) {
this.countries = countries;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class EndPojo {
private List<Country> countries;
public List<Country> getCountries() {
return countries;
}
public void setCountries(List<Country> countries) {
this.countries = countries;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Countries {
private List<Country> country;
public List<Country> getCountry() {
return country;
}
public void setCountry(List<Country> country) {
this.country = country;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Country {
private String name;
private String independence;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIndependence() {
return independence;
}
public void setIndependence(String independence) {
this.independence = independence;
}
}
}
此类接受输入json并通过将其打印到控制台将其转换为其他格式。此代码的输出是:
{
"countries" : [ {
"name" : "USA",
"independence" : "July 4, 1776"
} ]
}