IdleSun's Weblog

January 13, 2010

Single, or Double: That’s the question.

Filed under: JavaScript,JSON — idlesun @ 7:01 pm
Tags: ,

In JavaScript, single quote (‘) and double quote (“) are “kind of” interchangeable. So, the following two lines are all fine:

var helloText1 = 'Hello "Alice"'; 
var helloText2 = "Hello 'Alice'"; 

But, they are not the same in terms of actual string content in each variable because quotation marks are different.
This confusing difference can cause code errors when you try to combine strings to build a JSON object using a parser or eval() function. So, in the following code neither of last two lines will return a JSON object.

var name = "'name':'Alice'";
var phone = '"phone":"111-222-3333"';
var contact1 = eval("{" + name + "," + phone + "}");      // error
var contact2 = JSON.parse("{" + name + "," + phone + "}");   // error

Note that json2.js is used for JSON parser. Anyway, it is because different types of quotation marks can not be mixed in a string that represents a JSON object. That means the following code is fine:

var contact = JSON.parse("{'name':'Alice','phone':'111-222-3333'}");
var jsonText = JSON.stringify(contact);

One thing to note is that re-converted jsonText will contain double(“) for string quotation mark instead of single (‘). So, it will be like this if you check the content of jsonText:

{"name":"Alice","phone":"111-222-3333"}

As I mentioned in the beginning, it is confusing and can cause code errors. One way to avoid is to use one type of quotation mark consistently for JSON handling. My recommendation is “single outside and double inside“, which is like this:

var jsonContact = '{"name":"Alice","phone":"111-222-3333"}';

This way, it will be less confusing when you compare original input string with re-converted string from a parsed JSON object.
However, it is also important to understand the differences between quotation marks as wrapper code of string literal and quotation marks just as characters in a string. The confusing came from the thing that a quotation mark as character becomes wrapper code when string is eval()ed or parsed.
To understand better, take a look at the following code that shows how JSON object can be directly defined various ways including mixing quotation marks:

var contact1 = {"name":"Alice","phone":"111-222-3333"};
var contact2 = {'name':'Alice','phone':'111-222-3333'}; 
var contact3 = {'name':"Alice","phone":'111-222-3333'}; 

Note that all three lines are fine and create basically the same JSON object. So, if you converts all three objects to strings back, those strings will be the same with double quotation mark. Again, mixing is not a good coding practice and using double inside seems better and less confusing.

Advertisements

January 12, 2010

Gson – Complex Java Object with enum and list to JSON

Filed under: Java,JSON — idlesun @ 6:08 pm

Google GSON is pretty powerful with serializing a complex java object to json in one shot. This example shows the serialization  of a complex object that has a enum type member and nested list of simple objects:

public class TestMain {
	static enum Gender {Male, Female, NotKnown}

	static class Entry {
		public String name = "";
		public String phone = "";
		public Gender gender = Gender.NotKnown;
		public int birthYear;

		Entry(String name, String phone, Gender gender,int birthYear) {
			this.name = name;
			this.phone = phone;
			this.gender = gender;
			this.birthYear = birthYear;
		}
	}
	static class Contacts {
		public String name = "";
		public List entries = new ArrayList();
		Contacts(String name) {
			this.name = name;
		}
	}

	public static void main(String[] args) {
		// build contacts object
		Contacts contacts = new Contacts("My Contacts");
		contacts.entries.add(new Entry("John Doe", "123-234-3456", Gender.Male, 66));
		contacts.entries.add(new Entry("Jane Doe", "234-345-4567", Gender.Female, 67));

		// convert the contacts object to JSON string
		Gson gson = new Gson();
		System.out.println(gson.toJson(contacts));
	}
}

Here is the output:

{ 
  "name":"My Contacts",
  "entries":[
    {"name":"John Doe","phone":"123-234-3456","gender":"Male","birthYear":66},
    {"name":"Jane Doe","phone":"234-345-4567","gender":"Female","birthYear":67}
  ]
}

Nice, huh? Of course, check Gson User Guide for more details.

Create a free website or blog at WordPress.com.