Home > Net >  How to convert JSON object back to `Person` object java
How to convert JSON object back to `Person` object java

Time:11-17

I want to convert JSON object back to Person object java, but I am getting the following error java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at path $

Example Json file:

{
  "type":"set",
  "key":"person",
  "value":{
    "name":"Elon Musk",
    "car":{
      "model":"Tesla Roadster",
      "year":"2018"
    },
    "rocket":{
      "name":"Falcon 9",
      "launches":"87"
    }
  }
}
JsonObject jsonObject = new JsonParser().parse(input.readUTF()).getAsJsonObject();

Gson gson = new Gson();

for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
Person person = gson.fromJson(entry.getValue(), Person.class);
System.out.println(jsonFile);
}
@Getter
@Setter
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person  {
String type;
String key;
Value value;
}
@Data
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Getter
@ToString
public class Value  {
String name;
Map<String, String> car;
Map<String, String> rocket;
}

CodePudding user response:

The jsonObject in the example represents a Person so you don't have to iterate the jsonObject.entrySet() you have to use the jsonObject itself.

Person person = gson.fromJson(jsonObject, Person.class);
  • Related