如何在Android中使用Jackson解析器处理json数组解析

时间:2013-10-07 18:42:48

标签: java android json parsing jackson

这是我的json数据结构。它具有与此类似的大量数据。我正在使用Jackson解析器来解析它。

{
 "dealers":
 {
  "google.com":{"id":1,"merchantname":"google","status":"active"},
  "apple.com":{"id":2,"merchantname":"apple","status":"active"}
 }
}

代码:

    while (jParser.nextToken() != JsonToken.END_OBJECT) {
            jParser.nextToken();

            while (jParser.nextToken() != JsonToken.END_OBJECT) {
                jParser.nextToken();

                while (jParser.nextToken() != JsonToken.END_OBJECT) {
                    jParser.nextToken();
                    String fieldname = jParser.getCurrentName();
                    if (fieldname != null) {

                        if ("id".equals(fieldname)) {
                            jParser.nextToken();
                            if (jParser.getText() != null)
                                merchantID = jParser.getText();
                            else
                                merchantID = "";
                        }

                        if ("merchantname".equals(fieldname)) {
                            jParser.nextToken();
                            if (jParser.getText() != null)
                                merchantname = jParser.getText();
                            else
                                merchantname = "";
                        }

                        if ("status".equals(fieldname)) {
                            jParser.nextToken();
                            if (jParser.getText() != null)
                                name = jParser.getText();
                        }

                    }

                }
            }
        }

未正确解析数据。搞砸了jParser.nextToken()方法。谁能指出这里的错误?

1 个答案:

答案 0 :(得分:4)

JSON中的“dealer”属性代表Map<String, POJO_CLASS>。您可以轻松将其转换为以下POJO类:

class RootEntity {

    private Map<String, Entity> dealers;

    //getters,setters, toString
}

class Entity {

    private int id;
    private String merchantname;
    private String status;

    //getters,setters, toString
}

使用示例:

import java.io.File;
import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonProgram {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(new File("/data/x.json"), RootEntity.class));
    }
}

打印:

RootEntity [dealers={google.com=Entity [id=1, merchantname=google, status=active], apple.com=Entity [id=2, merchantname=apple, status=active]}]