Comment analyser les objets JSON à partir d'un JSONArray?
J'ai un très gros fichier JSON au format suivant:
[{"fullname": "name1", "id": "123"}, {"fullname": "name2", "id": "245"}, {"fullname": "name3", "id": "256"}]
Il ressemble à un JSONArray. Tous les enregistrements sont écrits sur la même ligne.
Pouvez-vous m'aider comment puis-je analyser ce fichier en utilisant Java. Je veux lire chaque objet JSON et afficher tous les fullname et ID. Voici ma tentative, mais mon code ne fonctionne pas:
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();
}
}
5 answers
Votre json est un JSONArray, donc lorsque vous l'analysez, vous devez l'analyser en tant que JSONArray.
JSONParser jsonParser = new JSONParser();
JSONArray a = (JSONArray) jsonParser.parse(new FileReader(src));
for (Object o : a) {
// access your object here.
}
Je suggérerais d'aller avec Jackson, en particulier l'API de streaming Jackson qui est parfaite pour analyser de grands tableaux comme celui-ci.
Voir cette réponse: https://stackoverflow.com/a/24838392/3765428
Vous pouvez utiliser Json.api java simple, ci-dessous est un code qui peut vous être utile
byte[] bFile = Files.readAllBytes(new File("C:/xyz.json").toPath());
JSONArray root = (JSONArray) JSONValue.parseWithException(bFile);
JSONObject rootObj = (JSONObject) root.get(0);
Vous pouvez obtenir des valeurs de JSONObject en fonction de la clé , cela dépend également du format de votre json car il pourrait y avoir des données json imbriquées. Vous devez donc extraire les données en conséquence . En dehors de cela, vous pouvez également utiliser jackson parser api ou GSON.
Ok les gens...viens de résoudre mon problème. Je poste la solution au cas où quelqu'un rencontrerait à nouveau le même problème, peut utiliser ma solution. Ma solution est en partie motivée par Rahul Rabhadiya. Merci, mec.
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();
}
Rendez votre vie facile et utilisez un ObjectMapper
.
De cette façon, vous définissez simplement un Pojo avec les mêmes propriétés que votre objet json.
Dans votre cas vous avez besoin d'un Pojo qui ressemble à ceci:
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;
}
}
Avec cela, vous n'avez qu'à faire:
ObjectMapper objectMapper = new ObjectMapper();
List<Person> persons = objectMapper.readValue(myInputStream, TypeFactory.defaultInstance().constructCollectionType(List.class, Person.class));
Il s'agit d'une approche sans tracas et sûre.
Dépendances nécessaires:
Https://github.com/FasterXML/jackson-databind
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>