如何从 JSONArray 解析 JSON 对象?

use*_*837 1 java arrays text json

我有一个非常大的 JSON 文件,格式如下:

[{"fullname": "name1", "id": "123"}, {"fullname": "name2", "id": "245"}, {"fullname": "name3", "id": "256"}]
Run Code Online (Sandbox Code Playgroud)

它看起来像一个 JSONArray。所有记录都写在同一行中。

你能帮我如何使用 Java 解析这个文件吗?我想读取每个 JSON 对象并显示所有全名和 ID。以下是我的尝试,但我的代码不起作用:

import org.apache.commons.lang3.StringEscapeUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JSONFileReaderDriver {

public static void main(String[] args) throws FileNotFoundException, 
IOException, ParseException 
{
 String filename="Aarau";
 String src="C:\\"+filename+".json";
 JSONParser parser = new JSONParser();
 JSONObject obj;
 try
    {
        BufferedReader br=new BufferedReader (new FileReader(src));  
        obj = (JSONObject) new JSONParser().parse(row);
        String fullname=obj.get("fullname");
        String id=obj.get("id");
        System.out.println ("fullname: "+fullname+" id: "+id);
    }catch(Exception e)
     {e.printStackTrace();}
   br.close();
  }
 }
Run Code Online (Sandbox Code Playgroud)

Her*_*erb 5

让您的生活更轻松,并使用ObjectMapper. 通过这种方式,您只需定义一个与 json 对象具有相同属性的 Pojo。

在你的情况下,你需要一个看起来像这样的 Pojo:

public class Person{
    private String fullname;
    private int id;

    public Person(String fullname, int id) {
        this.fullname = fullname;
        this.id = id;
    }

    public String getFullname() {
        return fullname;
    }

    public int getId() {
        return id;
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个,你只需要做:

ObjectMapper objectMapper = new ObjectMapper();
List<Person> persons = objectMapper.readValue(myInputStream, TypeFactory.defaultInstance().constructCollectionType(List.class, Person.class));
Run Code Online (Sandbox Code Playgroud)

这是一种轻松且类型安全的方法。

需要的依赖:

https://github.com/FasterXML/jackson-databind

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)