Json对象反序列化

时间:2014-12-31 12:37:03

标签: json deserialization flexjson

我想将JSON对象脱盐到Java Object(Location Class):

{
  "city": "TEST",
  "country": "TEST",
  "latitude": "1",
  "longitude": "1",
  "name": "TEST",
  "postalCode": "362001",
  "street": "TEST",
  "organization": 3
}

我的Java类是:

public class Location{
@ManyToOne
@ForeignKey(name = "FK_location__organization")
private Organization organization;

@NotNull
@Column(nullable = false)
private String name;

private boolean disabled;

private String street;
private String postalCode;
private String city;
private String country;

private Double latitude;
private Double longitude;

@Override
public String toString()
{
    return name;
}

public static List<Location> findAllLocationsOrderedByName()
{
    return entityManager().createQuery("SELECT o FROM Location o ORDER BY name ASC", Location.class).getResultList();}}

而且,组织类是:

public class Organization {
String name
}

尝试反序列化时出现以下错误:

flexjson.JsonNumber cannot be cast to java.util.Map
flexjson.factories.BeanObjectFactory.instantiate(BeanObjectFactory.java:17)
flexjson.ObjectBinder.bind(ObjectBinder.java:95)
flexjson.ObjectBinder.bindIntoObject(ObjectBinder.java:149)
flexjson.ObjectBinder.bind(ObjectBinder.java:95)
flexjson.ObjectBinder.bind(ObjectBinder.java:74)
flexjson.JSONDeserializer.deserialize(JSONDeserializer.java:158)
flexjson.factories.ClassLocatorObjectFactory.instantiate(ClassLocatorObjectFactory.java:38)

我使用以下代码(使用Flex JSON)进行反序列化:

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

public static Location Location.fromJsonToLocation(String json) {
    System.out.println(json);
    return new JSONDeserializer<Location>()
    .use(null, Location.class).deserialize(json);
}

2 个答案:

答案 0 :(得分:1)

看看Json的组织价值。它是整数值,但在Java对象中是Organization

答案 1 :(得分:0)

您可以使用ObjectMapper通过使用以下代码段将您的json数据转换为相应的Object:

ObjectMapper mapper = new ObjectMapper();
Location location= mapper.readValue(jsonData, Location.class);