Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a JSON without a key

Tags:

java

json

gson

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 { }?

like image 867
Hero Avatar asked Aug 28 '26 20:08

Hero


1 Answers

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.

like image 90
Christian Ascone Avatar answered Aug 30 '26 09:08

Christian Ascone



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!