从JSON文件中检索数组

时间:2012-11-21 12:51:30

标签: json jackson

我在JSON文件中有一个看起来像这样的数组

{ "fields": [
        {
            "name": "order_id",
            "type": "INTEGER",
            "position": 0
        },
        {
            "name": "district_id",
            "type": "INTEGER",
            "position": 1
        }]
}

我正在使用TREE MODEL检索数组“fields”的内容,我的代码看起来像这样..

public static void main(String[] args) throws JsonParseException, IOException {
File jsonFile = new File("metadata.json");
String theJsonString = jsonFile.toString();
String name = null;
String type =null;
int position = 0;
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
JsonNode rootNode = mapper.readTree(theJsonString);
JsonNode fields = rootNode.get("fields");
    if (fields != null) {

    for (int i = 0; i < fields.size(); i ++) {
        if(fields.has("name"))
            name = fields.get("name").getTextValue();
        if(fields.has("type"))
             type = fields.get("type").getTextValue();
        if(fields.has("position"))  
             position = fields.get("position").getIntValue();


        System.out.println(name);
    }
    }
  }

我在运行时遇到以下错误::

Exception in thread "main" org.codehaus.jackson.JsonParseException: Unexpected character ('/' (code 47)): maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)
 at [Source: java.io.StringReader@3eed2cab; line: 1, column: 2]
    at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1432)
    at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:385)
    at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:306)
    at org.codehaus.jackson.impl.ReaderBasedParser._skipComment(ReaderBasedParser.java:1498)
    at org.codehaus.jackson.impl.ReaderBasedParser._skipWSOrEnd(ReaderBasedParser.java:1474)
    at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:362)
    at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2761)
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2709)
    at org.codehaus.jackson.map.ObjectMapper.readTree(ObjectMapper.java:1533)
    at metadata.JSONParser.main(JSONParser.java:32)

我刚刚开始使用JSON,因此无法找到解决方案。有人可以帮我解决这个问题吗?

4 个答案:

答案 0 :(得分:1)

如果你想要文件metadata.json的内容,那么在文件上调用toString将不会给你这个。相反,它会给你一个字符串,其中包含文件名的路径。

而是从FileInputStream创建一个File,如下所示:

FileInputStream fis = new FileInputStream(jsonFile);

您可以将其与mapper

一起使用
JsonNode rootNode = mapper.readTree(fis);


当您遍历数组以访问数组中包含的每个fields.get(i)时,您可能还想调用JsonNode

答案 1 :(得分:0)

我有同样的问题,我最终通过此代码修复了问题,以获取JsonParser对象。

FileInputStream fis = new FileInputStream(path);
JsonParser jp = new JsonFactory().createParser(fis);

答案 2 :(得分:0)

前几天我遇到了同样的问题。 我的JSON 具有下一个语法:

{ "boxes": [
  {
    "name": "redBox.png",
    "version": 15
  },
  {
    "name": "blueBox.png",
    "version": 9
  }
]
}

我必须使用框版本创建方法,它返回POJO类。我的解决方案如下:

private static List<DataVersion> receiveDataVersions() throws IOException
    {
        String path = System.getProperty( "user.dir" ) + File.separator +
                        "versions.json";
        List<DataVersion> versions = new ArrayList<>();
        JsonNode folder = null;
        try( InputStream stream = new FileInputStream( path ) )
        {
            folder = new ObjectMapper().readTree( stream );
        }
        JsonNode boxes = folder.get( "inst" );
        boxes.forEach( version -> versions.add( new DataVersion(
                        version.get( "name" ).getTextValue(),
                        version.get( "version" ).getIntValue() ) ) );
        return versions;
    }
POJO如下:

public class DataVersion
{
    private String name;
    private int version;

    public DataVersion() {
    }

    public DataVersion(String name, int version) {
        this.name = name;
        this.version = version;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version){
        this.version=version;
    }


    @Override
    public String toString()
    {
        return "DataVersion [" + "name='" + name + '\'' + ", version=" +
                        version + ']';
    }
}

答案 3 :(得分:-1)

在您的代码中尝试此操作

jsonFactory.enable(JsonParser.Feature.ALLOW_COMMENTS);