如何解析JSONArray中的JSON对象? [英] How do I parse JSON objects from a JSONArray?
问题描述
我有一个非常大的JSON文件,格式如下:
I have a very large JSON file in the following format:
[{"fullname": "name1", "id": "123"}, {"fullname": "name2", "id": "245"}, {"fullname": "name3", "id": "256"}]
它看起来像一个JSONArray.所有记录都写在同一行中.
It looks like a JSONArray. All the records are written in the same line.
您能帮我如何使用Java解析此文件.我想读取每个JSON对象并显示所有全名和ID.以下是我的尝试,但是我的代码无法正常工作:
Can you help me how can I parse this file using Java. I want to read each JSON object and display all the fullname and ids. Below is my attempt, but my code is not working:
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();
}
}
推荐答案
好吧...刚解决了我的问题.我正在发布解决方案,以防有人再次遇到相同的问题,可以使用我的解决方案.我的解决方案部分是由Rahul Rabhadiya推动的.谢谢,伙计.
Okay folks...just solved my problem. I am posting the solution in case someone runs into the same issue again, can use my solution. My solution is partly motivated by Rahul Rabhadiya. Thanks, dude.
try{
row=br.readLine();
JSONArray root = (JSONArray) JSONValue.parseWithException(row);
for (int i=0;i<root.size();i++)
{
JSONObject rootObj = (JSONObject) root.get(i);
String fullname=(String) rootObj.get("fullname");
System.out.println (fullname);
}
}catch(Exception e)
{
e.printStackTrace();
}
这篇关于如何解析JSONArray中的JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!