【问题标题】:Deserializes data to the class将数据反序列化到类
【发布时间】:2017-12-02 13:46:36
【问题描述】:

我有这样一个程序,它使用 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
}

【问题讨论】:

  • 您正在尝试将 one 国家对象反序列化为 JSON 到国家的 array 对象。
  • 那我该怎么办?
  • 你想要一个国家,所以你应该告诉杰克逊你想要那个作为反序列化的结果:Country country = mapper.readValue(userDataJSON, Country.class);

标签: java json deserialization


【解决方案1】:

如下所示制作“userDataJSON”

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

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

【讨论】:

  • 我相信提问者正试图从 API 读取而不是静态字符串,因为 userDataJSON 目前在代码中已被注释掉。我不认为改变它是解决方案。另外,他们为什么要从国家类中删除构造函数?请务必解释为什么您的答案会奏效。
  • 我不认为'userDataJSON'是静态的。但问题中给出的任何内容都不是有效的 JSON,对于第二个问题 [stackoverflow.com/questions/39123030/…
猜你喜欢
  • 2013-11-26
  • 2018-11-16
  • 1970-01-01
  • 2018-10-15
  • 2023-03-14
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多