我按照http://tutorials.jenkov.com/java-json/jackson-objectmapper.html上的教程进行操作,并且syntex中没有错误。在代码中似乎没有问题,我已经使用向Netbeans项目添加库的标准方法在Netbeans中将JACKSON jar文件添加到库中。我仍然无法将JSON字符串转换为java对象。这是我的代码。
class Car {
private int doors;
private String brand;
public int getDoors() {
return doors;
}
public void setDoors(int doors) {
this.doors = doors;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
void printCar() {
System.out.println("car.brand = " + getBrand());
System.out.println("car.doors = " + getDoors());
}
}//class Car ends here.
以下是使用ObjectMapper类的方法readValue的代码
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ObjectMapperExampleWithString1 {
public static void main(String args[]) {
ObjectMapper objectMapper = new ObjectMapper();
String carJson
= "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
Car car = null;
try {
car = objectMapper.readValue(carJson, Car.class);
} catch (IOException ex) {
Logger.getLogger(ObjectMapperExampleWithString1.class.getName()).log(Level.SEVERE, null, ex);
}
if (car != null){
car.printCar();
}else{
System.out.println("Object car of type Car is null. Problem!!!");
}
}
}
这是我得到的例外。
运行: 线程" main"中的例外情况java.lang.NoSuchMethodError:com.fasterxml.jackson.databind.JavaType.isReferenceType()Z 在com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findDefaultDeserializer(BasicDeserializerFactory.java:1522) 在com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.findStdDeserializer(BeanDeserializerFactory.java:167) 在com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:132) 在com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:403) 在com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:352) 在com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264) 在com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244) 在com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142) at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:461) at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3804) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3698) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2714) at myJackson.ObjectMapperExampleWithString1.main(ObjectMapperExampleWithString1.java:18) Java结果:1 建立成功(总时间:0秒)