Hero
Hero

Reputation: 647

Create a JSON without a key

We wanted to create a JSON structure as below in Java

{
 [
  { 
   "key": "ABC001",
   "value": true 
  },
  { 
   "key": "ABD12",
   "value": false 
  },
  { 
   "key": "ABC002",
   "value": true 
  },
 ]
}

To implement this we created a class and had a list private property inside it. But that is creating a key values

class Response{
private List<Property> values;
 // setter getter for this private property
}

The output for this is

{
values : [
{
"key": "ABC001",
"value": true
},
......
]

Is there a way we create the array without the key and inside the { }?

Upvotes: 3

Views: 32100

Answers (2)

nonzaprej
nonzaprej

Reputation: 1600

So, for some reason you want an invalid json, which is an array contained between {}s. Here's how you can do it (I'll assume you use google-gson to make and parse jsons, since you didn't include your code):

// example of the creation of the list
List<Property> values = new ArrayList<>();
values.add(new Property("ABC001", true));
values.add(new Property("ABD12", false));
values.add(new Property("ABC002", true));
//

Gson gson = new Gson();
String json = gson.toJson(values, new TypeToken<List<Property>>() {}.getType());
json = "{" + json + "}";// gotta do what you gotta do...

Upvotes: 2

Christian Ascone
Christian Ascone

Reputation: 1177

Unfortunately, what you're trying to build is not a valid json. You can try to validate it here.

With this "json", for example, it would be impossible to read the array, because it has no key.

{
"foo_key" : "bar",
 [
  { 
   "key": "ABC001",
   "value": true 
  },
  { 
   "key": "ABD12",
   "value": false 
  },
  { 
   "key": "ABC002",
   "value": true 
  },
 ]
}

Parsing a json like this one, you could get "bar" because it has a key ("foo_key"), but how could you get the array?

The code you're using is already correct for a valid json.

Upvotes: 2

Related Questions