Need some help with java+json. My question is about the .json file. When parsing a file, I get null value. There may be a problem in the file itself, or i'm using the wrong parsing path. I have a class PhotocameraDTO:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class PhotocameraDTO {
@JsonProperty("id")
private int id;
@JsonProperty("name")
private String name;
@JsonProperty("type")
private String type;
@JsonProperty("sensor")
private String sensor;
@JsonProperty("lenses")
private String lenses;
@JsonProperty("display")
private String display;
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getSensor() {
return sensor;
}
public String getLenses() {
return lenses;
}
public String getDisplay() {
return display;
}
@Override
public String toString() {
return ("PhotocameraDTO [id=" + id + ", name=" + name + ", type=" + type + ", sensor=" + sensor + ", lenses="
+ lenses + ", display=" + display + "]");
}
And .json file (made a screenshot, since the code does not load as valid): http://prntscr.com/ls3fgn
And my class with main:
package task2;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
public class PhotocamerasTypes {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
FileInputStream fis = new FileInputStream("src/main/resources/photocameras.json");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
TypeFactory typeFactory = TypeFactory.defaultInstance();
List<PhotocameraDTO> photocameras = objectMapper.readValue(fis, typeFactory.constructCollectionType(ArrayList.class, PhotocameraDTO.class));
System.out.println(photocameras);
}
}
Result: [PhotocameraDTO [id=0, name=null, type=null, sensor=null, lenses=null, display=null]]
And now i found the mistake, but i don't now how to fix it. My json file has a structure like: { [{....},{.....}] } My code works if json file has structure like: [{....},{.....}]
But I don't how to fix my code for the structure with "{" at the beginning of the file.