115

我想JSON使用 json 简单库用 java 读取这个文件。

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

但我得到以下异常:

线程“主”java.lang.ClassCastException 中的异常:org.json.simple.JSONArray 无法在 javaapplication1.JavaApplication1.main(JavaApplication1.java:24) 处转换​​为 org.json.simple.JSONObject

有人可以告诉我我做错了什么吗?整个文件是一个数组,文件的整个数组中有对象和另一个数组(汽车)。但我不知道如何将整个数组解析为 java 数组。我希望有人可以帮助我解决我的代码中缺少的代码行。

谢谢

4

18 回答 18

94

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

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

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

有关参考,请参阅json-simple 解码示例页面上的“示例 1”。

于 2012-06-07T05:54:54.350 回答
56

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

ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);
于 2013-04-14T12:57:07.600 回答
18

添加杰克逊数据绑定:

<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);
于 2017-03-27T11:32:01.457 回答
13

从 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;
    }
于 2016-03-29T16:42:32.370 回答
7

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

将 JSONObject 用于类似 JSON 的简单 JSON {"id":"1","name":"ankur"},将 JSONArray 用于类似 .json 的 JSON 数组[{"id":"1","name":"ankur"},{"id":"2","name":"mahajan"}]

于 2017-02-24T13:38:34.777 回答
6

可能对面临相同问题的其他人有所帮助。您可以将文件加载为字符串,然后可以将字符串转换为 jsonobject 以访问这些值。

import java.util.Scanner;
import org.json.JSONObject;
String myJson = new Scanner(new File(filename)).useDelimiter("\\Z").next();
JSONObject myJsonobject = new JSONObject(myJson);
于 2017-08-08T09:45:56.100 回答
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();

        }

    }
}
于 2015-05-13T10:10:05.573 回答
4

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);
}
于 2021-07-31T21:56:17.327 回答
1

希望这个例子也有帮助

对于下面的 json 数组示例,我以类似的方式完成了 java 编码,如下所示:

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

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

{"EMPNO":275173,"EMP_NAME":"GK","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS 管理员"},

{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"项目分析员"}

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




}

}
于 2015-06-24T07:50:49.603 回答
1
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();
        }
    }

}
于 2017-10-23T11:47:29.560 回答
0

示例 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
}

第一个 If 语句将转换正文中的单个数据 第二个 if 语句将区分 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();
    }
}
于 2018-04-12T05:12:05.053 回答
0

以下是您的问题陈述的有效解决方案,

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);
    }
于 2021-12-17T06:39:22.350 回答
0
private static final JsonParser JSON_PARSER = new JsonParser();    
private static final String FILE_PATH = "configuration/data.json";

private JsonObject readJsonDataFromFile() {
    try {
        File indexFile = new File(FILE_PATH);
        String fileData = Files.toString(indexFile, Charsets.UTF_8);
        return (JsonObject) JSON_PARSER.parse(fileData);
    } catch (IOException | JsonParseException e) {
        String error = String.format("Error while reading file %s", FILE_PATH);
        log.error(error);
        throw new RuntimeException(error, e);
    }
}
于 2021-05-06T07:29:03.590 回答
0

导入 org 时会出现此问题。JSONObject 类的 json 库。相反,您需要导入 org.json.simple 库。

于 2020-12-29T09:53:23.207 回答
0

使用 Jackson 库的解决方案。通过验证 JSONLint.com 上的 json 然后使用 Jackson 对这个问题进行排序。下面是相同的代码。

 Main Class:-

String jsonStr = "[{\r\n" + "       \"name\": \"John\",\r\n" + "        \"city\": \"Berlin\",\r\n"
                + "         \"cars\": [\r\n" + "            \"FIAT\",\r\n" + "          \"Toyata\"\r\n"
                + "     ],\r\n" + "     \"job\": \"Teacher\"\r\n" + "   },\r\n" + " {\r\n"
                + "     \"name\": \"Mark\",\r\n" + "        \"city\": \"Oslo\",\r\n" + "        \"cars\": [\r\n"
                + "         \"VW\",\r\n" + "            \"Toyata\"\r\n" + "     ],\r\n"
                + "     \"job\": \"Doctor\"\r\n" + "    }\r\n" + "]";

        ObjectMapper mapper = new ObjectMapper();

        MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);

        for (MyPojo itr : jsonObj) {

            System.out.println("Val of getName is: " + itr.getName());
            System.out.println("Val of getCity is: " + itr.getCity());
            System.out.println("Val of getJob is: " + itr.getJob());
            System.out.println("Val of getCars is: " + itr.getCars() + "\n");

        }

POJO:

public class MyPojo {

private List<String> cars = new ArrayList<String>();

private String name;

private String job;

private String city;

public List<String> getCars() {
    return cars;
}

public void setCars(List<String> cars) {
    this.cars = cars;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
} }

  RESULT:-
         Val of getName is: John
         Val of getCity is: Berlin
         Val of getJob is: Teacher
         Val of getCars is: [FIAT, Toyata]

          Val of getName is: Mark
          Val of getCity is: Oslo
          Val of getJob is: Doctor
          Val of getCars is: [VW, Toyata]
于 2018-12-27T07:48:13.950 回答
0
public class JsonParser {

    public static JSONObject parse(String file) {
        InputStream is = JsonParser.class.getClassLoader().getResourceAsStream(file);
        assert is != null;
        return new JSONObject(new JSONTokener(is));
    }
}
// Read Json 
    JSONObject deviceObj = new JSONObject(JsonParser.parse("Your Json filename").getJSONObject(deviceID).toString());

执行逻辑迭代

于 2021-12-07T06:53:18.160 回答
-1

你的 json 文件看起来像这样

在此处输入图像描述

import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      try {
         Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
         JSONObject jsonObject = (JSONObject)obj;
         String name = (String)jsonObject.get("Name");
         String course = (String)jsonObject.get("Course");
         JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
         System.out.println("Name: " + name);
         System.out.println("Course: " + course);
         System.out.println("Subjects:");
         Iterator iterator = subjects.iterator();
         while (iterator.hasNext()) {
            System.out.println(iterator.next());
         }
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

输出是

Name: Raja
Course: MCA
Subjects:
subject1: MIS
subject2: DBMS
subject3: UML

从这里拿走

于 2020-09-29T09:36:23.557 回答
-2

您可以使用 readAllBytes。

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

于 2017-01-23T19:20:52.020 回答