1

I am trying to parse a json file in java. 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.

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.

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

5 Answers 5

1

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();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This seems like it would work. I cannot try it out because Lambda expressions are not supported in my source. I tried to rewrite it as a for each loop like this: for ( JSONObject jsonObject : jsonObjects.stream()) {} but there seems to be an error.
edited to foreach. please note this change: Long totalSales = (Long)jsonObject.get("totalSales");
0

Your data contains a JSON array, not a JSON object.

Change the line

JSONObject jsonObject =  (JSONObject) obj;

to

JSONArray jsonArray =  (JSONArray) obj;

This array will contain two JSONObjects.

Comments

0

you can use alibaba's fastjson.You can download fastjson jar file,this is 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:

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

Comments

0

Please find whole example below. 1) Create DTO class with your params like,

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

    //Getter and setters 

}

2) Then add Gson jar with min. version (2.2.4) - get online, or add dependency for maven structure.

3) Finally, add 2 lines in your code to get any parameter like,

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.

Comments

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

Try this one

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.