JSON String

String is a sequence of zero or more Unicode characters. Strings wrapped in double quotes using backslash escapes. A string is like a C or Java string and a character is represented as a single character string.

The JSON String interface allows a toJSONString() method so that a class can change the behavior of JSONObject.toString(), JSONArray.toString(), and JSONWriter.value(Object). The toJSONString method will be used instead of the default behavior of using the Object’s toString() method and quoting the result.
//public interface JSON String

String handling the following methods: –
1) toJSONString(): – This method is comes under the package name java.lang.String. The toJSONString method allows a class to produce its own JSON serialization. This method returns syntactically correct JSON text. It returns the JSON formatted value of this string, quoted for evaluating in a JavaScript interpreter. It is specified by toString in class JSONValue.

Eg: –

package com.site.core;
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
DataObject obj = new DataObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
try {
//write converted json data to a file named “file.json”
FileWriter writer = new FileWriter(“c:\\file.json”);
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(json);
 }
}

Output

{“data1”:100,”data2”:”hello”,”list”:[“String 1”,”String 2”,”String 3”]}

2) jQuery.parseJSON( json ): –  Passing is the deformed JSON string and it leads to result in an exception being thrown. Examples of deformed strings are given below.

  1. {test: 1} : – This type of string test does not have double quotes around it.
  2. {‘test’: 1}: – This ‘test’ is using single quotes instead of double quotes.

If we do not pass anything or empty string or null or undefined null will be returned from parseJSON.

Eg: –

var obj = jQuery.parseJSON('{“name”:”John”}');
alert( obj.name === “John” );

The eval() function can compile and execute any JavaScript and it leads to a potential security problem. So the safer method is to use a JSON parser to convert a JSON text to a JavaScript object. It will realize only JSON text and will not compile scripts.

It is safer to use a JSON parser to convert a JSON text to a JavaScript object. A JSON parser will recognize only JSON text and will not compile scripts. Browsers provide native JSON support and the native JSON support is included in newer browsers and the newest ECMAScript or JavaScript standard.

3) isString: – It returns this, as this is a JSONString. It overrides isString in class JSONValue. It returns a reference to a JSONString if this JSONValue is a JSONString or null otherwise.
java.lang.String stringValue(): -Returns the raw Java string value of this item.
public java.lang.String stringValue(): – Returns the raw Java string value of this item. java.lang.String toString(): – Returns the JSON formatted value of this string, quoted for evaluating in a JavaScript interpreter.

Object from String

We can convert JSON data to a JavaScript object and then use the data in a web page, by accomplishing this process by using string as input instead of file. Create a JavaScript string containing JSON syntax:

var txt = '{ “employees” : [' +
'{ “firstName”:”John” , “lastName”:”Doe” },' +
'{ “firstName”:”Anna” , “lastName”:”Smith” },' +
'{ “firstName”:”Peter” , “lastName”:”Jones” } ]}';

JSon syntax is the subset of JavaScript syntax and the eval() helps to convert JSON text into a JavaScript object. The working of eval() is, it helps the JavaScript compiler which will parse the JSON text and produce a JavaScript object. For avoiding the syntax error the text should be covered in parenthesis.

Token concept

Every JSON string is consider as a single token in streaming mode. We also called it incremental mode because each tokens will be processed incremental. In streaming mode, every JSON “string” is consider as a single token, and each tokens will be processed incremental, that why we call it “incremental mode”. For example,
Eg: –

var obj = eval (“(“ + txt + “)”);

JSON string provides a string concept.

Eg: –

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;
public class JacksonStreamExample {
 public static void main(String[] args) {
 try {
JsonFactory jfactory = new JsonFactory();
/*** read from file ***/
JsonParser jParser = jfactory.createJsonParser(new File(“c:\\user.json”));
// loop until token equal to “}”
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if (“name”.equals(fieldname)) {
 // current token is “name”,
 // move to next, which is “name”'s value
 jParser.nextToken();
 System.out.println(jParser.getText()); // display site
}
if (“age”.equals(fieldname)) {
 // current token is “age”, 
 // move to next, which is “name”'s value
 jParser.nextToken();
 System.out.println(jParser.getIntValue()); // display 29
}
if (“messages”.equals(fieldname)) {
 jParser.nextToken(); // current token is “[“, move next
 // messages is array, loop until token equal to “]”
 while (jParser.nextToken() != JsonToken.END_ARRAY) {
 // display msg1, msg2, msg3
 System.out.println(jParser.getText()); 
 }
}
 }
 jParser.close();
 } catch (JsonGenerationException e) {
 e.printStackTrace();
 } catch (JsonMappingException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 } }

Warning
The array parsing is a bit tricky, read code comments for explanation.
Output

site
29
msg 1
msg 2
msg 3

The JSONString class is given below:-

<strong>java.lang.Object</strong>
<strong> com.google.gwt.json.client.JSONValue</strong>
<strong> com.google.gwt.json.client.JSONString</strong>

Example of representing JSON string is given below: – public class JSONString extends JSONValue JSONString(java.lang.String value): – It will create a new JSONString from the supplied String. JSONStringisString(): – Returns this, as this is a JSONString. POJOA pojo, with initialized values. Later use Gson to convert this object to/from JSON formatted string. Eg: –

package com.site.core;
import java.util.ArrayList;
import java.util.List;
public class DataObject {
private int data1 = 100;
private String data2 = “hello”;
private List<String> list = new ArrayList<String>() {
 {
add(“String 1”);
add(“String 2”);
add(“String 3”);
 }
};
//getter and setter methods
@Override
public String toString() {
 return “DataObject [data1=“ + data1 + “, data2=“ + data2 + “, list=“
+ list + “]”;
}
}