Reputation: 11075
Thanks for the question about the mismatch of property name. However, I have made them consistent but same error throws.
I'm using Jackson to convert JSON array to Java object array.
The code is as simple as below, here is the code entry:
import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;
import jackson.vo.User;
public class JsonConvertTest {
public static void main(String args[]){
try{
ObjectMapper objectMapper = new ObjectMapper();
File file = new File("results.json");
User[] users= objectMapper.readValue(file, User[].class);
}catch(Exception e){
e.printStackTrace();
}
}
}
Here is the value object,
package jackson.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
@JsonProperty("firstName")
String firstName;
@JsonProperty("lastName")
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Here is the JSON array:
{
"users":[
{ "firstName":"Tom", "lastName":"Jackson"},
{ "firstName":"Jenny", "lastName":"Mary"},
{ "firstName":"Red", "lastName":"Blue"},
{ "firstName":"Jason", "lastName":"John"},
{ "firstName":"May", "lastName":"Black"}
]
}
The output is:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `jackson.vo.User[]` out of START_OBJECT token
at [Source: (File); line: 1, column: 1]
Thanks for your help in advance.
Upvotes: 2
Views: 9241
Reputation: 915
Root level object in your JSON file is a JSON object, yet you are telling jackson to read the file as an array of users.
Try with the following contents:
[
{ "firstName":"Tom", "lastName":"Jackson"},
{ "firstName":"Jenny", "lastName":"Mary"},
{ "firstName":"Red", "lastName":"Blue"},
{ "firstName":"Jason", "lastName":"John"},
{ "firstName":"May", "lastName":"Black"}
]
Upvotes: 2
Reputation: 3914
This is because of the property mismatch. You can try this
public class User {
@JsonProperty("firstname")
String firstName;
@JsonProperty("lastname")
String lastName;
}
@JsonProperty
is used to indicate external property name, name used in data format (JSON or one of other supported data formats)
Upvotes: 0
Reputation: 2065
Note the spelling of lastname(your POJO) vs lastName(the Json). Either change your pojo to firstName and lastName to match those of your JSON or set annotation above each field like below:
public class User {
@JsonProperty("firstname");
String firstName;
@JsonProperty("lastname");
String lastName;
Upvotes: 0
Reputation: 10346
I am fairly certain this is an issue of case sensitivity. Jackson by default looks for property "getters" so you have "getFirstName". But, your JSON file is "firstname".
Try again with the case sensitivity the same between your source json file and your class.
Upvotes: 0