将数据反序列化到类中

时间:2017-12-02 13:46:36

标签: java json deserialization

我有一个使用API​​ REST获取数据的程序,并在JTextArea中显示它。一切都好,但我需要通过反序列化来修改这个程序。我需要将从API获得的数据反序列化到类Country,然后才显示它。我试过但得到了错误:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of model.Country[] out of START_OBJECT token at [Source: {"nativeName":"latitude","longitude"}; line: 1, column: 1]

这是我的主要课程(我尝试进行反序列化):

public void actionPerformed(ActionEvent evt) {

    /*ObjectMapper mapper = new ObjectMapper();
    String userDataJSON = "{\"nativeName\":\"latitude\",\"longitude\"}";
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

    try {
        Country[] userFromJSON = mapper.readValue(userDataJSON, Country[].class);
        System.out.println(userFromJSON);
    } catch (IOException e1) {
        System.out.println(e1);
    }*/
            ...
                textField.selectAll();
                textArea.setCaretPosition(textArea.getDocument().getLength());
            }
        } catch (Exception e) {
        }
    }
}

我的班级国家:

public class Country {

@JsonProperty
private String name; 
@JsonProperty
public String nativeName;
@JsonProperty
private String latitude; 
@JsonProperty
private String longitude; 
@JsonProperty
private String currencyCode; 

public Country(String name, String nativeName, String latitude, String longitude, String currencyCode) {
    super();
    this.name = name;
    this.nativeName = nativeName;
    this.latitude = latitude;
    this.longitude = longitude;
    this.currencyCode = currencyCode;

// getters & setters
}

1 个答案:

答案 0 :(得分:-1)

制作'userDataJSON',如下所示

String userDataJSON = "[{\"name\":\"test\", \"nativeName\":\"Test\", \"latitude\":\"45.898\",\"longitude\":\"76.8989\", \"currencyCode\":\"code\"}]";

并从Country类中删除构造函数。