Originerd
Originerd

Reputation: 694

How to add values at JSONObject in Java?

I added values using like json.put("key", "value").

The result was {"key": "value"}.

But I want to get result like {key: "value"}

How do I do?

Upvotes: 0

Views: 771

Answers (2)

Maas
Maas

Reputation: 1357

Json uses quotes to increase the posible types of key and value.

Example:

{ Some key : Some Vaue } - Invalid

{ Some key : Some : Vaue } - Invalid

This is not a valid JSON as any Json parser will fail to identify the "space" between words. In order to avoid such situations, JSON objects are defined with quotes.

{ "Some key" : "Some : Vaue" } - This is valid

This is the reason for any JSON parser to return the key and values quoted.

An example to help you

public static void main(String[] args)
    {
        Gson gson = new Gson();
        
        //String json = "{key : \"value\"}"; - Valid
        
        //String json = "{key : value}"; - Valid
        
        //String json = "{key : some : value}"; // Invalid

        String json = "{key : \"some : value\"}"; // Valid
        
        Map<String, String>  map = gson.fromJson(json, Map.class);
        
        System.out.println(map.size());
        
        System.out.println(gson.toJson(map));
        
    }

Upvotes: 0

jorrin
jorrin

Reputation: 512

That is not possible as JSON Objects' keys are always enclosed in quotes. The values can have no quotes if it's Booloean or number like :

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "height_cm": 167.6
  }

Upvotes: 2

Related Questions