繁体   English   中英

使用最新的Jackson解析器库在Android设备上解析JSON

[英]Parse JSON on Android device using latest Jackson Parser library

这是JSON响应str的示例:

{"myServiceMethodResult":[{"BoolPropertyOfFooClass":false,"StringPropertyOfFooClass":"tstString", "Bar":[{"BoolPropertyOfBarClass":false,"StringProperyOfBarClass":"tst"}]
}]
}

服务正在返回列表

List<Foo> myServiceMethod(){

return new List<Foo> myFooList
}

这些是类:

@JsonRootName(value = "myServiceMethodResult")
Class Foo{

public boolean BoolPropertyOfFooClass
public String  StringPropertyOfFooClass


@JsonProperty(value = "Bar")
public List<Bar> myBar;


public boolean getBoolPropertyOfFooClass(){

return BoolPropertyOfFooClass;
}

public void setBoolPropertyOfFooClass(bool value){
this.BoolPropertyOfFooClass = value

}

public String getStringPropertyOfFooClass(){

return StringPropertyOfFooClass;
}

public void setBoolPropertyOfFooClass(String value){
this.StringPropertyOfFooClass = value

}

public List<Bar> myBar() {
        return myBar;
    }

    public void setmyBar(List<Bar> value) {
        this.myBar= value;
    }

}

我使用的是杰克逊(Jackson)解析器,首先将JSON字符串解析为一个对象的速度令人惊讶(尽管该文件很大(2 MB)

  String jsonStr = sh.makeServiceCall(serviceUrl/MethodName, ServiceHandler.POST, json_content_parameters);

       ObjectMapper mapper = new ObjectMapper();
       mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
       JsonNode node = null;
     myFooInstance=  mapper.readValue(new StringReader(jsonStr), new TypeReference<List<Foo>>(){}); 

mapper.readValue遇到异常myServiceResult与预期的不匹配(“列表”)。 此外,如果我使用readTree函数,则需要5秒钟(但不是hittign异常)。 有没有更好的方法可以更快地获得对象,

更进一步,我无法弄清楚如何在Foo对象内映射Bar对象的List。 我可以使用以下代码行设置属性:

TypeReference<List<Foo>> typeRef = new TypeReference<List<Foo>>(){};
myInstanceFoo= mapper.readValue(node.traverse(), typeRef);

所以我有我的Foo对象列表,但是我无法使用类似的东西使List进入列表。 关于持续时间问题或设置内部List对象的任何帮助将不胜感激

跟踪:

com.fasterxml.jackson.databind.JsonMappingException: Root name 'MyMethodResponse' does not match expected ('List') for type [collection type; class java.util.List, contains [simple type, class com.package.Foo]]
 at [Source: java.io.StringReader@411dc790; line: 1, column: 2]

由于看起来响应包含在一个单成员对象实例中,因此可以选择使用以下方法注释Foo类:

@JsonRootName("MyMethodResponse")

重要提示:名称为FIXED。

但是,您尚未完成。 您需要配置ObjectMapper以使用此注释:

mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE);

您还有另一个问题。 即,您的List<Bar>在POJO中的名称为myBar ,但在生成的JSON中的名称为Bar 您需要将您的注释myBar与现场@JsonProperty

@JsonProperty("Bar")

万一有人偶然发现了一个相同的问题,我想通了。 如果JSON格式为序列化Foo类

{"response":[{"propertyOfFooClass":"something"
}]
} 

您需要创建包含Foo类列表的根类

公共类RootWrapper {

private List<Foo> foo;

public List<Foo> getFoos() {
    return channels;
}

@JsonProperty("response")
public void setFoos(List<Foo> fooList) {
    this.foo= fooList;
}


RootWrapper mj = mapper.readValue(jsonStr, RootWrapper.class);

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM