简体   繁体   English

使用 Jackson 从单个文件中读取多个 JSON 对象到 Java 中

[英]Reading multiple JSON Objects from a single file into Java with Jackson

So I've done my best to research similar issues like this, but I'm fairly new to Java and JSON, so I apologize if this is redundant.因此,我已尽最大努力研究类似的问题,但我对 Java 和 JSON 还很陌生,所以如果这是多余的,我深表歉意。 I'm working on a simple text based RPG for my Java class this semester, and I want to store character information and location information in either XML or JSON.本学期我正在为我的 Java 课程开发一个基于文本的简单 RPG,我想将字符信息和位置信息存储在 XML 或 JSON 中。 I've given both a try, and seem to be getting farther with JSON and Jackson.我都试过了,似乎在使用 JSON 和 Jackson 方面走得更远。 I've written some tester code to try this out before implementing in my game, but basically I want each game "location" to have an integer ID#, some string information, and a list of exitNodes (which will eventually correspond to other locations in the game).在我的游戏中实现之前,我已经编写了一些测试人员代码来尝试这一点,但基本上我希望每个游戏“位置”都有一个整数 ID#、一些字符串信息和一个 exitNode 列表(最终将对应于其他位置在游戏里)。 Here is an example of my JSON:这是我的 JSON 示例:

{
"1":{
    "enterInfo":"Test Location Information",
    "exitNodes":[2,3]
},
"2":{
    "enterInfo":"More Test Location Info",
    "exitNodes":[4,5]
},
"3":{
    "enterInfo":"More Test Location Info",
    "exitNodes":[6,7]
}
}

I'm guessing I could organize my JSON a bit better, but ideally I want to be able to grab an object by it's number, and get the "enterInfo" and "exitNodes" back.我猜我可以更好地组织我的 JSON,但理想情况下我希望能够通过它的编号抓取一个对象,并获得“enterInfo”和“exitNodes”。 I've spent hours trying different things without success, but the best I can do is grab the whole JSON document as a JsonNode which just gives me the entire structure, but not an individual object.我花了几个小时尝试不同的事情但没有成功,但我能做的最好的事情就是将整个 JSON 文档作为 JsonNode 抓取,它只给我整个结构,而不是单个对象。

Here is a test class (minus constructor/getters/setters/methods) I'm trying to get the JSON into:这是一个测试类(减去构造函数/getters/setters/methods),我试图将 JSON 放入:

public class ObjectTest{
    int id;
    String enterInfo;
    int[] exitNodes;
}

And here is what I have working so far, I realize that I'm not even close to achieving my goal here, but I'm out of ideas and the documentation is starting to get confusing, so I've removed my attempts to isolate one of the objects in the JSON file and instantiate an "ObjectTest" object:这是我到目前为止所做的工作,我意识到我什至没有接近实现我的目标,但是我没有想法并且文档开始变得混乱,所以我已经删除了我的隔离尝试JSON 文件中的对象之一并实例化“ObjectTest”对象:

package jacksontester;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;


    public class JackSONTester {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode localeTemp = mapper.readTree(new File("src/jacksontester/TestMeJSON.json"));
        System.out.println(localeTemp);
    }
}

Not that it really matters, but here is what prints out:并不是说它真的很重要,但这是打印出来的:

{"1":{"enterInfo":"Test Location Information","exitNodes":[2,3]},"2":{"enterInfo":"More Test Location Info","exitNodes":[4,5]},"3":{"enterInfo":"More Test Location Info","exitNodes":[6,7]}}

What I want to achieve is being able to create an "ObjectTest" object with the values from my JSON.我想要实现的是能够使用我的 JSON 中的值创建一个“ObjectTest”对象。 Again, sorry if this is a duplicate, I've read through numerous posts already, but I'm new here...再次,对不起,如果这是重复的,我已经阅读了很多帖子,但我是新来的......

EDIT: I'm realizing now that my JSON file should probably be organized more like this:编辑:我现在意识到我的 JSON 文件应该更像这样组织:

{"locations":[
     {   "id":0,
         "enterInfo":"Test Location Information",
         "exitNodes":[1,2]
     },
     {   "id":1,
         "enterInfo":"More Test Location Info",
         "exitNodes":[2,3]
     },
     {   "id":2,
         "enterInfo":"More Test Location Info",
         "exitNodes":[4,5]
     }
     ]
     }

I would need to then create a list of objects defined by the JSON?然后我需要创建一个由 JSON 定义的对象列表?

This should solve it for you:这应该为您解决:

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

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

public class JacksonTester {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        List<ObjectTest> myObjects = mapper.readValue(jsonFile(), new TypeReference<List<ObjectTest>>(){});
        System.out.println(myObjects);
    }

    private static File jsonFile() {
        return new File("src/main/resources/test.json");
    }
}

Using this as JSON:将其用作 JSON:

[{   
 "id":0,
 "enterInfo":"Test Location Information",
 "exitNodes":[1,2]
},
{   "id":0,
      "enterInfo":"Test Location Information",
      "exitNodes":[1,2]
}]

Reference 参考

EDIT编辑
Forgot to say that the fields need to have setters or to be public忘了说字段需要有setter或者是public

' '

This is Quite helpful for me, but when i am reading json as below i am getting error can u help me . 这对我很有帮助,但是当我按以下方式阅读json时,我遇到了错误,您可以帮我吗。

{

"items": [ { "name": "Bachat Bazar", "parent": "G1", "uom": "pc", "category": "\ Not Applicable" }, { "name": "GASTEK ENGINEERING PVT LTD", "parent": "G1", "uom": "pc", "category": "\ Not Applicable" }, { "name": "Ind Swift Laboratories LTD Chandigarh", "parent": "G1", "uom": "pc", "category": "\ Not Applicable" }, { "name": "Ind Swift Ltd Punjab", "parent": "G1", "uom": "pc", "category": "\ Not Applicable" }, { "name": "Purnima kirana store", "parent": "G1", "uom": "pc", "category": "\ Not Applicable" }, { "name": "TS INFOTECH INDIA PVT LTD", "parent": "G1", "uom": "pc", "category": "\ Not Applicable" } ] } “ items”:[{“ name”:“ Bachat Bazar”,“ parent”:“ G1”,“ uom”:“ pc”,“ category”:“ \\ u0004不适用”},{“ name”:“ GASTEK ENGINEERING PVT LTD”,“父母”:“ G1”,“ uom”:“ pc”,“类别”:“ \\ u0004不适用”},{“名称”:“ Ind Swift Laboratories LTD Chandigarh”,“父母”: “ G1”,“ uom”:“ pc”,“类别”:“ \\ u0004不适用”},{“ name”:“ Ind Swift Ltd Punjab”,“ parent”:“ G1”,“ uom”:“ pc “,” category“:” \\ u0004不适用“},{” name“:” Purnima kirana store“,” parent“:” G1“,” uom“:” pc“,” category“:” \\ u0004不适用“},{” name“:” TS INFOTECH INDIA PVT LTD“,” parent“:” G1“,” uom“:” pc“,” category“:” \\ u0004不适用“}]}

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

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