我正在编写一个接收Json String的程序,将其转换为Java对象并将其打印到屏幕上。非常简单的东西,但我的问题是让程序读取Json字符串。
下面是类,以及创建Json String的测试类,并调用NameList.java类,它根据Json字符串中的对象数创建Name对象列表。
继承错误:无法识别的字段"名称" (Class sample.NameList),未在[来源:java.io.StringReader@1a407d53;标记为可忽略; line:1,column:12](通过引用链:sample.NameList [" Name"])
我在线检查了多个来源,很多人建议只使用列表文件中的注释来修复它。其他人说要更改Xxx的名称。的getXxx'到JSON文件中的根名称。我尝试了两种选择,似乎没有任何选择。 任何帮助将非常感激, 感谢
public class UserTest {
public static void main(String[] args) throws JSONException{
String jsonStr = "{"
+ "\"Names\":[{\"field\":\"John\","
+ "\"value\":\"3\"},{"
+ "\"field\":\"Ali\","
+ "\"value\":4 }]}";
ObjectMapper mapper = new ObjectMapper();
try {
System.out.println("before obj creation");
SelectList testObject = mapper.readValue(jsonStr, NameList.class);
System.out.println("Created the class");
System.out.print(testObject);
} catch (Exception e) {
System.out.println("caught the error");
e.printStackTrace();
}
}
}
public class Name {
private String field;
private String value;
//getters and setters
@Override
public String toString() {
return "Name{" +
"field='" + field + '\'' +
", value='" + value + '\'' +
'}';
}
}
public class SelectList {
@JsonProperty("Select")
private List<Name> name;
/**
* @return the selected statements
*/
public List<Name> getName() {
return name;
}
/**
* @param the names to set
*/
public void setName(List<Name> names) {
this.name = names;
}
}
答案 0 :(得分:0)
您的代码和json中存在一些问题
#define inline
已编辑:已添加maven依赖项
public class NameList {
@JsonProperty("Names")
private List<Name> name;//field name should be same as json field or use annnotation
/**
* @return the selected statements
*/
public List<Name> getName() {
return name;
}
/**
* @param names to set
*/
public void setName(List<Name> names) {
this.name = names;
}
}
public class Name {
private String field;
private String value;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "Name{" +
"field='" + field + '\'' +
", value='" + value + '\'' +
'}';
}
}
public class NameListTest {
@Test
public void test1() { // values should be in quotes if they are string literal
String jsonStr = "{"
+ "\"Names\":[{\"field\":\"John\","
+ "\"value\":\"3\"},{"
+ "\"field\":\"Ali\","
+ "\"value\":4 }]}";
ObjectMapper mapper = new ObjectMapper();
try {
NameList testObject = mapper.readValue(jsonStr, NameList.class);
System.out.print(testObject);
} catch (Exception e) {
e.printStackTrace();
}
}
}