如何在Java

时间:2019-05-24 09:42:48

标签: java json

我正在尝试在Java中解析json文件。但是,我一直收到错误消息。 这是我要解析的文件:

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

这是我尝试过的:

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

这是我收到的错误:

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

很抱歉,这是一个愚蠢的问题,有一个简单的解决方案。我是JSON新手。

编辑:

我决定继续下面的代码。但是,我无法将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();
    }
}

最终编辑(已解决问题):

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

5 个答案:

答案 0 :(得分:1)

请尝试以下操作:

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

答案 1 :(得分:0)

您的数据包含JSON数组,而不是JSON对象。

更改行

JSONObject jsonObject =  (JSONObject) obj;

JSONArray jsonArray =  (JSONArray) obj;

此数组将包含两个JSONObject

答案 2 :(得分:0)

您可以使用阿里巴巴的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>

导入此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);
    }
}

答案 3 :(得分:0)

请在下面找到整个示例。 1)使用参数

创建DTO类
class JsonParam {
    private String name;
    private int totalSales;
    private int salesPeriod;
    private float experienceMultiplier;

    //Getter and setters 

}

2)然后加入最少的Gson jar。版本(2.2.4)-上线,或添加对Maven结构的依赖关系。

3)最后,在代码中添加2行以获取任何类似参数,

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

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

在上面的语句中,我使用了0索引,您可以根据需要使用for循环。

答案 4 :(得分:0)

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

尝试这个