Comment lire un fichier json en java avec une bibliothèque JSON simple


Je veux lire ce fichier JSON avec java en utilisant la bibliothèque simple json.

Mon fichier JSON ressemble à ceci:

[  
    {  
        "name":"John",
        "city":"Berlin",
        "cars":[  
            "audi",
            "bmw"
        ],
        "job":"Teacher"
    },
    {  
        "name":"Mark",
        "city":"Oslo",
        "cars":[  
            "VW",
            "Toyata"
        ],
        "job":"Doctor"
    }
]

C'est le code java que j'ai écrit pour lire ce fichier:

package javaapplication1;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JavaApplication1 {
    public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        try {     
            Object obj = parser.parse(new FileReader("c:\\file.json"));

            JSONObject jsonObject =  (JSONObject) obj;

            String name = (String) jsonObject.get("name");
            System.out.println(name);

            String city = (String) jsonObject.get("city");
            System.out.println(city);

            String job = (String) jsonObject.get("job");
            System.out.println(job);

            // loop array
            JSONArray cars = (JSONArray) jsonObject.get("cars");
            Iterator<String> iterator = cars.iterator();
            while (iterator.hasNext()) {
             System.out.println(iterator.next());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

, Mais j'obtiens l'exception suivante:

Exception dans le thread "main" java.lang.ClassCastException: org.json.simple.JSONArray ne peut pas être converti en org.json.simple.JSONObject à javaapplication1.JavaApplication1.principal (JavaApplication1.java:24)

Quelqu'un peut-il le dire moi ce que je fais de mal? Le fichier entier est un tableau et il y a des objets et un autre tableau (cars) dans tout le tableau du fichier. Mais je ne sais pas comment je peux analyser tout le tableau dans un tableau java. J'espère que quelqu'un peut m'aider avec une ligne de code qui me manque dans mon code.

Merci

Author: OO7, 2012-06-07

12 answers

Le fichier entier est un tableau et il y a des objets et d'autres tableaux (par exemple des voitures) dans tout le tableau du fichier.

Comme vous le dites, la couche la plus externe de votre blob JSON est un tableau. Par conséquent, votre analyseur retournera un JSONArray. Vous pouvez ensuite obtenir JSONObjects à partir du tableau ...

  JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));

  for (Object o : a)
  {
    JSONObject person = (JSONObject) o;

    String name = (String) person.get("name");
    System.out.println(name);

    String city = (String) person.get("city");
    System.out.println(city);

    String job = (String) person.get("job");
    System.out.println(job);

    JSONArray cars = (JSONArray) person.get("cars");

    for (Object c : cars)
    {
      System.out.println(c+"");
    }
  }

Pour référence, voir "Exemple 1" sur l' json simple décodage exemple page.

 57
Author: Greg Kopff, 2018-01-14 09:08:19

Vous pouvez utiliser la bibliothèque Jackson et simplement utiliser ces 3 lignes pour convertir votre fichier json en objet Java.

ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);
 23
Author: Mady, 2013-04-14 12:57:07

Vous pouvez utiliser Gson pour ce.
GSON est une bibliothèque Java qui peut être utilisée pour convertir des objets Java en leur représentation JSON. Il peut également être utilisé pour convertir une chaîne JSON en un objet Java équivalent.

Jetez un oeil à cette Conversion JSON en Java

 5
Author: Sumit Singh, 2017-05-23 12:18:25

Lecture de JsonFile

public static ArrayList<Employee> readFromJsonFile(String fileName){
        ArrayList<Employee> result = new ArrayList<Employee>();

        try{
            String text = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);

            JSONObject obj = new JSONObject(text);
            JSONArray arr = obj.getJSONArray("employees");

            for(int i = 0; i < arr.length(); i++){
                String name = arr.getJSONObject(i).getString("name");
                short salary = Short.parseShort(arr.getJSONObject(i).getString("salary"));
                String position = arr.getJSONObject(i).getString("position");
                byte years_in_company = Byte.parseByte(arr.getJSONObject(i).getString("years_in_company")); 
                if (position.compareToIgnoreCase("manager") == 0){
                    result.add(new Manager(name, salary, position, years_in_company));
                }
                else{
                    result.add(new OrdinaryEmployee(name, salary, position, years_in_company));
                }
            }           
        }
        catch(Exception ex){
            System.out.println(ex.toString());
        }
        return result;
    }
 5
Author: Teddy, 2016-03-29 17:01:23
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Delete_01 {
    public static void main(String[] args) throws FileNotFoundException,
            IOException, ParseException {

        JSONParser parser = new JSONParser();
        JSONArray jsonArray = (JSONArray) parser.parse(new FileReader(
                "delete_01.json"));

        for (Object o : jsonArray) {
            JSONObject person = (JSONObject) o;

            String strName = (String) person.get("name");
            System.out.println("Name::::" + strName);

            String strCity = (String) person.get("city");
            System.out.println("City::::" + strCity);

            JSONArray arrays = (JSONArray) person.get("cars");
            for (Object object : arrays) {
                System.out.println("cars::::" + object);
            }
            String strJob = (String) person.get("job");
            System.out.println("Job::::" + strJob);
            System.out.println();

        }

    }
}
 3
Author: Delvin, 2015-05-13 10:10:05

Ajouter Jackson databind:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0.pr2</version>
</dependency>

Créer une classe DTO avec des champs associés et lire le fichier JSON:

ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);
 3
Author: Justas, 2017-03-27 11:32:01

Utilisez google-bibliothèque simple.

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Veuillez trouver l'exemple de code ci-dessous:

public static void main(String[] args) {
    try {
        JSONParser parser = new JSONParser();
        //Use JSONObject for simple JSON and JSONArray for array of JSON.
        JSONObject data = (JSONObject) parser.parse(
              new FileReader("/resources/config.json"));//path to the JSON file.

        String json = data.toJSONString();
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

Utilisez JSONObject pour un JSON simple comme {"id":"1","name":"ankur"} et JSONArray pour un tableau de JSON comme [{"id":"1","name":"ankur"},{"id":"2","name":"mahajan"}].

 2
Author: Ankur Mahajan, 2017-02-24 13:38:34

Pourrait être utile pour quelqu'un d'autre confronté au même problème.Vous pouvez charger le fichier en tant que chaîne, puis convertir la chaîne en jsonobject pour accéder aux valeurs.

import java.util.Scanner;
import org.json.JSONObject;
String myJson = new Scanner(new File(filename)).useDelimiter("\\Z").next();
JSONObject myJsonobject = new JSONObject(myJson);
 1
Author: Srijan Sharma, 2017-08-08 09:45:56

J'espère que cet exemple aide aussi

J'ai fait du codage java de la même manière pour l'exemple de tableau json ci-dessous comme suit:

Voici le format de données json : stocké en tant que "EMPJSONDATA.json "

[{"EMPNO":275172,"EMP_NAME":"Rehan","date de naissance":"29-02-1992","MJ":"10-06-2013","RÔLE":"DÉVELOPPEUR JAVA"},

{"EMPNO":275173,"EMP_NAME":"G. K","date de naissance":"10-02-1992","MJ":"11-07-2013","RÔLE":"WINDOWS ADMINISTRATEUR"},

{"EMPNO":275174,"EMP_NAME":"Abiram","date de naissance":"10-04-1992","MJ":"12-08-2013","RÔLE":"ANALYSTE de PROJET"}

{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","date de naissance":"10-04-1992","MJ":"12-08-2013","RÔLE":"ANALYSTE de PROJET"}]

public class Jsonminiproject {

public static void main(String[] args) {

      JSONParser parser = new JSONParser();

    try {
        JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json"));
        for (Object o : a)
        {
            JSONObject employee = (JSONObject) o;

            Long no = (Long) employee.get("EMPNO");
            System.out.println("Employee Number : " + no);

            String st = (String) employee.get("EMP_NAME");
            System.out.println("Employee Name : " + st);

            String dob = (String) employee.get("DOB");
            System.out.println("Employee DOB : " + dob);

            String doj = (String) employee.get("DOJ");
            System.out.println("Employee DOJ : " + doj);

            String role = (String) employee.get("ROLE");
            System.out.println("Employee Role : " + role);

            System.out.println("\n");

        }


    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




}

}
 0
Author: rehan hanar, 2015-06-24 07:50:49
package com.json;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class ReadJSONFile {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        try {
            Object obj = parser.parse(new FileReader("C:/My Workspace/JSON Test/file.json"));

            JSONArray array = (JSONArray) obj;
            JSONObject jsonObject = (JSONObject) array.get(0);

            String name = (String) jsonObject.get("name");
            System.out.println(name);

            String city = (String) jsonObject.get("city");
            System.out.println(city);

            String job = (String) jsonObject.get("job");
            System.out.println(job);

            // loop array
            JSONArray cars = (JSONArray) jsonObject.get("cars");
            Iterator<String> iterator = cars.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}
 0
Author: P RAJESH, 2017-10-23 11:47:29

Exemple Json

{
    "per_page": 3,
    "total": 12,
    "data": [{
            "last_name": "Bluth",
            "id": 1,
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
            "first_name": "George"
        },
        {
            "last_name": "Weaver",
            "id": 2,
            //"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
            "first_name": "Janet"
        },
        {
            "last_name": "Wong",
            "id": 3,
            //"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg",
            "first_name": "Emma"
        }
    ],
    "page": 1,
    "total_pages": 4
}

La première instruction If convertira les données uniques du corps Deuxièmement, l'instruction if différenciera l'objet JsonArray

public static String getvalueJpath(JSONObject responseJson, String Jpath ) {
        Object obj = responseJson;
        for(String s : Jpath.split("/"))
            if (s.isEmpty())
                if(!(s.contains("[") || s.contains("]")))
                    obj = ((JSONObject) obj).get(s);
                else
                    if(s.contains("[") || s.contains("]"))
                        obj = ((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("//[")[1].replaceAll("]", "")));

        return obj.toString();
    }
}
 0
Author: lokesh sharma, 2018-04-12 06:31:15

Vous pouvez utiliser readAllBytes.

return String(Files.readAllBytes(Paths.get(filePath)),StandardCharsets.UTF_8);

 -3
Author: Rajat Mahajan, 2017-01-23 19:20:52