Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON only allows one top level value?

I have the following Java Object:

public class PersonDetails {
    private Person person;
    private List<Relative> relatives;

    public PersonDetails() {};

    //getters and setters

    }

I am trying to create Stub JSON for this so that I can parse it to a Java Object using GSON.

When I try to use the below JSON, but I get the error:

JSON only allows one top level value

How can I alter my JSON to make it valid?

My Current JSON:

{
    "Person": {

        "id": "123",
        "name: "stubName"
    },
    [
     "Relative": {

        "name": "relative1",
        "relation: "mother"

     }

    ]
}
like image 320
java123999 Avatar asked Aug 29 '26 02:08

java123999


1 Answers

I think your JSON structure is incorrect, GSON is expecting something like:

{
  "person": {
      // Person object
  },
  "relatives": [ // Mind the plural!
      {
           //Relative object
      },
      {
           //another Relative object
      }
  ]
}

Rationale: In general any JSON library will examine your beans looking for public setters. If you have a setter like setPerson(Person p), then it will remove the "set" prefix and then will switch the case of the next letter ("P" becomes "p"), so it will try to create a Person object and then insert it in a person attribute.

But then again I think there is something else wrong: that error complains that you have a JSON string like: "{....},{....}", so you have 2 or more top level (aka root) objects, which is not allowed in the JSON standard notation.

like image 116
Pablo Lozano Avatar answered Aug 31 '26 22:08

Pablo Lozano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!