我做了一个相当基本的Java对象,它包含三个变量;一个String,一个String []和一个String [] []。这使用杰克逊完美地编码成JSON对象,我能够打印它。但是尝试使用Jackson解析这个String不会给我回来的对象,它只会抛出IOException。
以下代码可用于复制我的问题。
对象:
public class CityJSON {
String[] currentCityList;
String brokenCity;
String[][] cityCosts;
CityJSON(String[] ccl, String bc, String[][] cc){
currentCityList = ccl;
brokenCity = bc;
cityCosts = cc;
}
public String[] getCurrentCityList() {
return currentCityList;
}
public void setCurrentCityList(String[] currentCityList) {
this.currentCityList = currentCityList;
}
public String getBrokenCity() {
return brokenCity;
}
public void setBrokenCity(String brokenCity) {
this.brokenCity = brokenCity;
}
public String[][] getCityCosts() {
return cityCosts;
}
public void setCityCosts(String[][] cityCosts) {
this.cityCosts = cityCosts;
}
}
编码器和解析器:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Tester {
public static void main(String args[]){
String[] cities = {"A city", "Another city"};
String[] one = {"cost1", "cost2"};
String[] two = {"cost3", "cost4"};
String[][] twod = new String[2][2];
twod[0] = one;
twod[1] = two;
CityJSON json = new CityJSON(cities, "myCity", twod);
String gen = "";
ObjectMapper mapper = new ObjectMapper();
try {
gen = mapper.writeValueAsString(json);
} catch (JsonProcessingException ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(gen);
try {
CityJSON ob = new ObjectMapper().readValue(gen, CityJSON.class);
} catch (IOException ex) {
System.out.println("FAILED");
}
}
}
将触发catch语句,导致打印“FAILED”。
答案 0 :(得分:1)
IOException声明:
com.fasterxml.jackson.databind.JsonMappingException:找不到类型[simple type,class CityJSON]的合适构造函数:无法从JSON对象实例化(缺少默认构造函数或创建者,或者可能需要添加/启用类型信息? ) 在[来源:{“currentCityList”:[“一个城市”,“另一个城市”],“brokenCity”:“myCity”,“cityCosts”:[[“cost1”,“cost2”],[“cost3”,“ cost4" ]]}; line:1,column:2] 在com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
因此,创建一个无参数构造函数,或使用@JsonCreator
注释现有构造函数,并使用@JsonProperty("propertyName")
注释该构造函数的args - 例如
@JsonCreator
CityJSON(
@JsonProperty("currentCityList") String[] ccl,
@JsonProperty("brokenCity") String bc,
@JsonProperty("cityCosts")String[][] cc
){
currentCityList = ccl;
brokenCity = bc;
cityCosts = cc;
}