I'm writing a program that receives a Json String, converts it to Java object and prints it out to the screen. Pretty simple stuff, but my problem is getting the program to read the Json String.
Below is the classes, along with the test class which creates a Json String, and calls the class NameList.java which creates a list of Name objects depending on the number of objects in the Json String.
Heres the error: Unrecognized field "Name" (Class sample.NameList), not marked as ignorable at [Source: java.io.StringReader@1a407d53; line: 1, column: 12] (through reference chain: sample.NameList["Name"])
I checked multiple sources online, many advised to just use annnotations in the list file which should fix it. Others say to change the name of the Xxx in' getXxx' to the name of the root in the JSON file. I tried both options, and none seemed to have made a difference. Any help would be much appreciated, Thanks
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;
}
}