0

I have a json file and using below code to convert json into java POJO

    reader = new JsonReader(new InputStreamReader(responseStream, "UTF-8"));
    Gson gson = new GsonBuilder().create();
    reader.beginObject();
    while (reader.hasNext()) {
        Example st = gson.fromJson(reader, Example.class);
    }

my json structure is as:

{
  "$id": "students.json",
  "type": "object",
  "properties": {
    "project": {
      "$id": "project",
      "projectList": [
        "ABC"
      ]
    },
    "students": {
      "$id": "/properties/students",
      "type": "array",
      "subelements": {
        "properties": {
          "id": {
            "$id": "/properties/students/subelements/properties/id",
            "examples": [
              "Y"
            ]
          },
          "dep": {
            "$id": "/properties/students/subelements/properties/dep",
            "examples": [
              "X"
            ]
          }
        },
        "required": [
          "id",
          "dep"
        ]
      }
    }
  },
  "required": [
    "project"
  ]
}

And I only need students.subelements.id.examples[0] and students.subelements.dep.examples[0] from list of students currently my java object classes are:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "project",
    "elements"
})
public class Example {

    /**
     * The project
     * (Required)
     * 
     */
    @JsonProperty("project")
    @JsonPropertyDescription("The project code")
    private String project;
    @JsonProperty("elements")
    private List<Student> elements = null;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();
}

    //student class
    public class Student{
    private String id;
    private String dep;
    }

and I am facing below exception:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NAME at line 2 column 4 path $.

so please help me what will be my exact java object class according to provided json and I will get only required fields from that class ?

9
  • you have trailing commas in your json Commented Sep 18, 2018 at 12:23
  • These are part of data Commented Sep 18, 2018 at 12:26
  • students.subelements.dep.examples array is followed by a comma - this is not valid because it's the last field of dep Commented Sep 18, 2018 at 12:30
  • Issue is still same without comma too. I have edited in question too Commented Sep 18, 2018 at 12:33
  • there are more trailing comma's - use json lint tool. projectList": [ "ABC"], Commented Sep 18, 2018 at 12:34

1 Answer 1

1

Reason for error

To begin, the reason for the error is that, after you first call reader.beginObject();, the JSON reader will go to second line "$id", which is a NAME type for JSONToken.
And gson.fromJson(reader, Student.class); is expecting the next JSON value is of BEGIN_OBJECT type, hence the error occur.

Solution

Since only a small part from the JSON is required, and the path is not trivial, we can not create a POJO to retrieve data by direct mapping. As @user10375692 suggests, we can implement JsonDeserializer interface for more flexible mapping. In the deserialize method, we can use JSONObject API to retrieve data from specific path. Following is an example.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class JsonToPojo {
    public static void main(String[] args) {
        String json = getJson();

        GsonBuilder gsonBuilder = new GsonBuilder();

        JsonDeserializer<Example> deserializer = new JsonDeserializer<Example>() {

            @Override
            public Example deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                Example example = new Example();
                JsonObject jsonObject = json.getAsJsonObject();
                example.setProject(jsonObject.getAsJsonObject("properties").getAsJsonObject("project")
                        .getAsJsonArray("projectList").get(0).getAsString());

                JsonObject subElementProperties = jsonObject.getAsJsonObject("properties").getAsJsonObject("students")
                        .getAsJsonObject("subelements").getAsJsonObject("properties");
                JsonArray idExamples = subElementProperties.getAsJsonObject("id").getAsJsonArray("examples");
                JsonArray depExamples = subElementProperties.getAsJsonObject("dep").getAsJsonArray("examples");
                List<Student> students = new ArrayList<Student>();
                for (int i = 0; i < idExamples.size(); i++) {
                    Student student = new Student();
                    student.setId(idExamples.get(i).getAsString());
                    student.setDep(depExamples.get(i).getAsString());
                    students.add(student);
                }
                example.setStudents(students);
                return example;
            }
        };
        gsonBuilder.registerTypeAdapter(Example.class, deserializer);

        Gson customGson = gsonBuilder.create();
        Example customObject = customGson.fromJson(json, Example.class);
        System.out.println(customObject.getStudents() + ", " + customObject.getProject());
    }

    private static String getJson() {
        return "{                                                  "
                + "  \"$id\": \"students.json\",                   "
                + "  \"type\": \"object\",                         "
                + "  \"properties\": {                             "
                + "    \"project\": {                              "
                + "      \"$id\": \"project\",                     "
                + "      \"projectList\": [                        "
                + "        \"ABC\"                                 "
                + "      ]                                         "
                + "    },                                          "
                + "    \"students\": {                             "
                + "      \"$id\": \"subproject\",                  "
                + "      \"type\": \"array\",                      "
                + "      \"subelements\": {                        "
                + "        \"properties\": {                       "
                + "          \"id\": {                             "
                + "            \"$id\": \"id\",                    "
                + "            \"examples\": [                     "
                + "              \"Y\"                             "
                + "            ]                                   "
                + "          },                                    "
                + "          \"dep\": {                            "
                + "            \"$id\": \"dep\",                   "
                + "            \"examples\": [                     "
                + "              \"X\"                             "
                + "            ]                                   "
                + "          }                                     "
                + "        },                                      "
                + "        \"required\": [                         "
                + "          \"id\",                               "
                + "          \"dep\"                               "
                + "        ]                                       "
                + "      }                                         "
                + "    }                                           "
                + "  },                                            "
                + "  \"required\": [                               "
                + "    \"project\"                                 "
                + "  ]                                             "
                + "}                                               ";
    }
}
Sign up to request clarification or add additional context in comments.

9 Comments

you are right about the reason of error. Can I change my java class such that below line automatically map json data to java object: Student st = gson.fromJson(reader, Student.class);
I removed this line reader.beginObject();.. Now I am getting no error but data is not mapped to POJO, java object contains empty fields
Can you post Student class also?
updated classes in question.. Now these are classes which I have made so far
Is it possible to replace the Element class in my solution to your Student class since both class have same property?
|

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.