简体   繁体   English

如何在Java中将json文件解析为json对象

[英]How to parse a json file into a json object in java

I am trying to parse a json file in java. 我正在尝试在Java中解析json文件。 However I keep receiving an error. 但是,我一直收到错误消息。 This is the file I am trying to parse: 这是我要解析的文件:

[{
        "name": "John Smith",
        "totalSales": 250,
        "salesPeriod": 10,
        "experienceMultiplier": 0.5
    },
    {
        "name": "David Prowless",
        "totalSales": 250,
        "salesPeriod": 10,
        "experienceMultiplier": 0.5
    }
]

This is what I have tried: 这是我尝试过的:

public static void main(String[] args)
{
    JSONParser parser = new JSONParser();

    try {     
        Object obj = parser.parse(new FileReader("data.json"));

        JSONObject jsonObject =  (JSONObject) obj;

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

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

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

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


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

This is the error I receive: 这是我收到的错误:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at mentormate.json.MentormateJson.main(MentormateJson.java:23)
Java Result: 1

I apologize if this is a silly question with a simple solution. 如果这是一个简单的解决方案,是一个愚蠢的问题,我深表歉意。 I am new to json. 我是json的新手。

EDIT: 编辑:

I have decided to go along with the code below. 我决定继续下面的代码。 However, I cannot set the for each loop right to iterate through object in the json file. 但是,我无法将for每个循环的权限设置为遍历json文件中的对象。

 public static void main(String[] args) {

 JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(new FileReader("data.json"));

        JSONArray jsonObjects =  (JSONArray) obj;

        for ( JSONObject jsonObject : jsonObjects) {
            String name = (String) jsonObject.get("name");
            System.out.println(name);

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

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

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

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

FINAL EDIT (PROBLEM SOLVED): 最终编辑(已解决问题):

public static void main(String[] args)   {
    JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(new FileReader("data.json"));

        JSONArray jsonObjects =  (JSONArray) obj;

        for (Object o : jsonObjects) {
            JSONObject jsonObject = (JSONObject) o;
            String name = (String) jsonObject.get("name");
            System.out.println(name);

            Long totalSales = (Long) jsonObject.get("totalSales");
            System.out.println(totalSales);

            Long salesPeriod = (Long) jsonObject.get("salesPeriod");
            System.out.println(salesPeriod);

            Double exp = (Double) jsonObject.get("experienceMultiplier");
            System.out.println(exp);

            System.out.println();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

Please try this: 请尝试以下方法:

 public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(new FileReader("data.json"));

        JSONArray jsonObjects =  (JSONArray) obj;

        for (Object o : jsonObjects) {
            JSONObject jsonObject = (JSONObject) o;
            String name = (String) jsonObject.get("name");
            System.out.println(name);

            Long totalSales = (Long)jsonObject.get("totalSales");
            System.out.println(totalSales);

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

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

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

Your data contains a JSON array, not a JSON object. 您的数据包含JSON数组,而不是JSON对象。

Change the line 换线

JSONObject jsonObject =  (JSONObject) obj;

to

JSONArray jsonArray =  (JSONArray) obj;

This array will contain two JSONObject s. 此数组将包含两个JSONObject

you can use alibaba's fastjson.You can download fastjson jar file,this is pom xml: 您可以使用阿里巴巴的fastjson。可以下载fastjson jar文件,这是pom xml:

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.56</version>
</dependency>

when you import this jar,you can code like this: 导入此jar时,可以这样编写:

import com.alibaba.fastjson.JSONObject;

import java.util.List;

public class MainTest {
    public static void main(String[] args) {
        String json = "[\n" +
                "{\n" +
                "\"name\": \"John Smith\",\n" +
                "\"totalSales\": 250,\n" +
                "\"salesPeriod\": 10,\n" +
                "\"experienceMultiplier\": 0.5\n" +
                "},\n" +
                "{\n" +
                "\"name\": \"David Prowless\",\n" +
                "\"totalSales\": 250,\n" +
                "\"salesPeriod\": 10,\n" +
                "\"experienceMultiplier\": 0.5\n" +
                "}\n" +
                "]";
        List<JSONObject> jsonObjects = JSONObject.parseArray(json,JSONObject.class);
        jsonObjects.stream().forEach(System.out::print);
    }
}

Please find whole example below. 请在下面找到整个示例。 1) Create DTO class with your params like, 1)使用您的参数创建DTO类,

class JsonParam {
    private String name;
    private int totalSales;
    private int salesPeriod;
    private float experienceMultiplier;

    //Getter and setters 

}

2) Then add Gson jar with min. 2)然后加入最小的Gson罐。 version (2.2.4) - get online, or add dependency for maven structure. 版本(2.2.4)-上线,或为maven结构添加依赖项。

3) Finally, add 2 lines in your code to get any parameter like, 3)最后,在代码中添加2行以获取任何参数,例如,

List<JsonParam> jsonParams = new Gson().fromJson(json, new TypeToken<List<JsonParam>>() {}.getType());

System.out.println(jsonParams.get(0).getName());

In above statement, I have used 0 index, you can use for-loop as per your requirement. 在上面的语句中,我使用了0索引,可以根据需要使用for循环。

try {
        JSONParser parser = new JSONParser();
        try {
            Object obj = parser.parse(new FileReader("./test.json"));
            // parsing the JSON string inside the file that we created earlier.
            JSONArray jsonarray = (JSONArray) obj;

            for (int i = 0; i < jsonarray.size(); i++) {

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

                long totalSales = (long) jsonObject.get("totalSales");
                System.out.println(totalSales);

                long salesPeriod = (long) jsonObject.get("salesPeriod");
                System.out.println(salesPeriod);

                Double exp = (Double) jsonObject.get("experienceMultiplier");
                System.out.println(exp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

Try this one 试试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM