如何使用简单的JSON库将JSON文件读入Java

144

我想使用json simple库在java中读取这个JSON文件。

我的JSON文件长这样:

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

这是我编写的Java代码,用于读取此文件:

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();
        }
    }
}

但是我收到了以下异常:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject at javaapplication1.JavaApplication1.main(JavaApplication1.java:24)

有人能告诉我我做错了什么吗?整个文件都是一个数组,其中包含对象和另一个数组(cars)。但我不知道如何将整个数组解析成java数组。我希望有人能帮我补充我代码中缺失的代码行。

谢谢


请参考以下答案:https://dev59.com/92s05IYBdhLWcg3wFN4h - Muhammed Fasil
不想使用数据模型?如果您使用Gson,那就像吃个馅饼一样容易,只需像这样解析:List<YOUR_USER_MODEL> info = new Gson().fromJson(YOUR_JSON_STRING, new TypeToken<List<YOUR_USER_MODEL>>() {}.getType()) - Mostafa Nazari
23个回答

108

整个文件是一个数组,这个数组中有对象和其他数组(例如汽车)。

正如你所说的,JSON数据的最外层是一个数组。因此,解析器将返回一个JSONArray。您可以从数组中获取JSONObject……

  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+"");
    }
  }

参考示例1,参见json-simple解码示例页面。


4
这很好用!请注意:在这个例子中使用原样导入(即使用'simple'),否则将无法允许 'for each'。 错误的方式: import org.json.JSONArray; import org.json.JSONObject; 正确的方式: import org.json.simple.JSONArray; import org.json.simple.JSONObject; - Krishna Sapkota
位置156处出现了意外的标记左花括号({)。 - Spartan
1
如何给FileReader提供相对路径,可能是从/resources文件夹中。 - prime
4
parser是哪个库(import)中的? - user25
1
JSONParser parser=new JSONParser(); - Infinity
显示剩余7条评论

82

您可以使用jackson库,并简单地使用以下3行将您的JSON文件转换为Java对象。

ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);

1
我可以知道下载ObjectMapper jar的链接吗? - Rence Abishek
3
@RenceAbishek,你可以使用import com.fasterxml.jackson.databind.ObjectMapper;导入它。 - Ron Kalian

24

添加Jackson databind:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0.pr2</version>
</dependency>
创建DTO类并添加相关字段,然后读取JSON文件:
ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);

15

读取Json文件

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;
    }

9
使用 google-simple 库。
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

请查看下面的示例代码:

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();
    }
}

对于简单的 JSON 数据,如 {"id":"1","name":"ankur"},请使用 JSONObject。对于 JSON 数组,如 [{"id":"1","name":"ankur"},{"id":"2","name":"mahajan"}],请使用 JSONArray。


7

如果有人遇到同样的问题,这可能会有所帮助。您可以将文件加载为字符串,然后将字符串转换为jsonobject以访问值。

import java.util.Scanner;
import org.json.JSONObject;
String myJson = new Scanner(new File(filename)).useDelimiter("\\Z").next();
JSONObject myJsonobject = new JSONObject(myJson);

5

Gson 可以在这里使用:

public Object getObjectFromJsonFile(String jsonData, Class classObject) {
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonObject object = (JsonObject) parser.parse(jsonData);
    return gson.fromJson(object, classObject);
}

1
JsonParser()已被弃用,请使用gson.fromJson()代替。 - Hephaestus

4
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();

        }

    }
}

2
以下是解决你问题的可行方案:

首先,你需要按照以下步骤执行:

File file = new File("json-file.json");
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(file));
    JSONArray jsonArray = new JSONArray(obj.toString());
    for (int i = 0; i < jsonArray.length(); i++) {
      JSONObject jsonObject = jsonArray.getJSONObject(i);
      System.out.println(jsonObject.get("name"));
      System.out.println(jsonObject.get("city"));
      System.out.println(jsonObject.get("job"));
      jsonObject.getJSONArray("cars").forEach(System.out::println);
    }

1

希望这个例子也能对您有所帮助

我已经以类似的方式用Java编写了下面的JSON数组示例:

以下是JSON数据格式:存储为“EMPJSONDATA.json”

[{"EMPNO":275172,"EMP_NAME":"Rehan","DOB":"29-02-1992","DOJ":"10-06-2013","ROLE":"JAVA DEVELOPER"},

{"EMPNO":275173,"EMP_NAME":"G.K","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS ADMINISTRATOR"},

{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}

{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}]

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();
    }




}

}

位置156处出现了意外的标记左花括号({)。 - Spartan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接