简体   繁体   English

Android JSON解析(Jackson)

[英]Android JSON Parsing (Jackson)

I've read a bunch of different articles, comparations and tutorials that are using different JSON-Libraries for parsing (and creating) JSON into Java Objects. 我读过许多不同的文章,比较和教程,它们使用不同的JSON库将JSON解析(和创建)成Java Object。 Anyway I think that I've got the facts right cause I've decided to use the JSON library called Jackson. 无论如何,我认为事实是正确的,因为我决定使用称为Jackson的JSON库

GSON is simple and robust but way to slow acording to me. GSON简单而强大,但是对我来说却很慢。 So I decided to actually try this Jackson thing out but, it seems like the parsing is a little bit more confusing here than with GSON. 因此,我决定实际尝试一下Jackson的事情,但是,与GSON相比,这里的解析似乎有些混乱。

The data-type of the value that I want to parse is simply an Boolean . 我要解析的值的数据类型只是Boolean

This is what the JSON that I'm trying to parse looks like: 这就是我要解析的JSON的样子:

{"FooResult":true}

So what I actually need help with is selecting the value from the key FooResult and then parse its value into an Boolean. 因此,我实际上需要帮助的是从键FooResult选择值,然后将其值解析为布尔值。

This Is what I've done so far: 到目前为止,这是我所做的:

String json = getString(request);
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, Boolean.class);

But this code obviously gives me an error cause I haven't selected that it is the FooResult key that I'm interested in reading & parsing into an Boolean. 但是这段代码显然给了我一个错误原因,因为我没有选择我感兴趣的FooResult键,并将其解析为布尔值。

You should create a new class like this: 您应该创建一个新的类,如下所示:

class MyClass {
   public boolean FooResult;
}

And use this code to load the data: 并使用以下代码加载数据:

MyClass myObject = mapper.readValue(json, MyClass.class);

Then you can access the value with myObject.FooResult 然后,您可以使用myObject.FooResult访问该值

Ok this is lame. 好的,这很la脚。 Even lamer when I rethink about it. 当我重新考虑它时,甚至是拉默。 The problem the whole time have been that the class of the object that you want to parse needs to be static . 一直以来,问题是您要解析的对象的类必须是静态的 I've tried what Simon suggested like four or five times before I even posted this question today but the problem all time was that the class wasn't static . 在今天我甚至发表这个问题之前,我已经尝试了西蒙建议的四到五次,但问题一直在于课堂并非静态的

So now it finally works. 所以现在终于可以了。

static class FooClass
{  
    public boolean FooResult; 
}

And for the parsing process. 并用于解析过程。

String json = getString(request);
ObjectMapper mapper = new ObjectMapper();
FooClass fooClass = null;
try 
{
    fooClass = mapper.readValue(json, FooClass.class);
}
boolean result = fooClass.FooResult;

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

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