我有一个非常大的 JSON 文件,格式如下:
[{"fullname": "name1", "id": "123"}, {"fullname": "name2", "id": "245"}, {"fullname": "name3", "id": "256"}]
它看起来像一个 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();
}
}
让您的生活变得轻松并使用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;
}
}
这样你只需要做:
ObjectMapper objectMapper = new ObjectMapper();
List<Person> persons = objectMapper.readValue(myInputStream, TypeFactory.defaultInstance().constructCollectionType(List.class, Person.class));
这是一种无麻烦且类型安全的方法。
需要的依赖:
https://github.com/FasterXML/jackson-databind
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)