簡體   English   中英

如何在Java中將json文件解析為json對象

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

我正在嘗試在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();
    }
}

請嘗試以下方法:

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

您的數據包含JSON數組,而不是JSON對象。

換線

JSONObject jsonObject =  (JSONObject) obj;

JSONArray jsonArray =  (JSONArray) obj;

此數組將包含兩個JSONObject

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

請在下面找到整個示例。 1)使用您的參數創建DTO類,

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

    //Getter and setters 

}

2)然后加入最小的Gson罐。 版本(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循環。

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

試試這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM