2

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

{
 "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() 方法。谁能指出这里的错误?

4

1 回答 1

4

JSON 中的“经销商”属性表示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]}]
于 2013-10-07T19:17:32.400 回答