JSON data

Suppose that you have the following JSON data to be stored as a Java string:

{"plastic": { 
  "id": "98751", 
  "singleuse": { 
    "item": [ 
      {"value": "Water Bottle", "replaceWith": "Steel Bottle()"}, 
      {"value": "Straw", "replaceWith": "Ban Straws"}, 
      {"value": "Spoon", "replaceWith": "Steel Spoon"} 
    ] 
  } 
}} 

The following code shows how you would perform this action with the traditional String class, escaping the double quotes within the data by using and adding a newline escape sequence:

String data = 
"{"plastic": { 
" + 
  ""id": "98751", 
" + 
  ""singleuse": { 
" + 
    ""item": [ 
" + 
      "{"value": "Water Bottle", "replaceWith": "Steel 
Bottle()"}, " + "{"value": "Straw", "replaceWith": "Ban Straws"}, " + "{"value": "Spoon", "replaceWith": "Steel Spoon"} " + "] " + "} " + "}}";

To be honest, it took me quite a while to write the preceding code, escaping the double quotes with the backslash. As you can see, this code is not readable.

The following example shows how you can code the same JSON data using raw string literals, without giving up the code readability:

String data =  
```{"plastic": { 
  "id": "98751", 
  "singleuse": { 
    "item": [ 
      {"value": "Water Bottle", "replaceWith": "Steel Bottle()"}, 
      {"value": "Straw", "replaceWith": "Ban Straws"}, 
      {"value": "Spoon", "replaceWith": "Steel Spoon"} 
    ] 
  } 
}}```;

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.26.108