这是我上一个问题的扩展 Extract specific value from complex JSON in java。我有解决方案,但我想尝试从bean类的json字符串中提取3个值。对于给定的json结构。 json结构在链接中。
我正在使用以下代码来调用jackson:
mainbean obj = mapper.readValue(file, mainbean.class);
System.out.println(obj.clientPayload.e.h.getAk());
我为mainbean类的整个层次结构生成了POJO:
public class mainbean {
public Cpld cp;
public Cpld getCp() {
return Cp;
}
public void setCp(Cpld cp) {
this.cp= cp;
}
public SPL getSp() {
return sp;
}
public void setSp(SPL sp) {
this.sp= sp;
}
private SPL sp;
@Override
public String toString() {
return "mainbean [cp=" + cp+ "]";
}
}
后跟Cpld类
public class Cpld {
public E e;
public E getE() {
return e;
}
public void setE(E e) {
this.e = e;
}
public String toString(){
return "E string" + e;
}
}
然后是上课
public class E {
public H h;
public H getH() {
return h;
}
public void setH(H h) {
this.h = h;
}
public C c;
public B b;
public TT tt;
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
public TT getTt() {
return tt;
}
public void setTt(TT tt) {
this.tt = tt;
}
}
等等......我得到了一个例外
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class JsonPath.Cpld] from JSON String; no single-String constructor/factory method (through reference chain: JsonPath.mainbean["clientPayload"])
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator._createFromStringFallbacks(StdValueInstantiator.java:419)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:295)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromString(BeanDeserializer.java:405)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:117)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:336)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:89)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:290)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:112)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2577)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1764)
有人能够在这里指出我正确的方向...... 在此先感谢您的任何帮助
答案 0 :(得分:0)
因为CP
的顶级JSON对象的值是JSON对象的字符串表示形式,而不是JSON对象本身,所以Cpld
类需要一个显式构造函数,该构造函数接受一个字符串并将其反序列化为该对象的属性。
答案 1 :(得分:0)
只需在Clpd类中添加一个空构造函数