Parsing JSON string in Java

Posted on 08-01-2013 10:16 by graham
This tutorial shows you how to convert a JSON string into JSONObject and JSONArray objects.

Parsing a simple object


Let's say we want to parse a JSON string containing a simple object with a few attributes:
{
name: "Kamila",
age: "26",
height: "152",
occupation: "architect"
}

Assuming that our JSON string is stored in the variable jsonString, the code to parse this object into an associative array and print its key-value pairs looks as follows:
JSONParser parser = new JSONParser();
JSONObject parsedJson = (JSONObject)parser.parse(jsonString);

for (Object fieldName : parsedJson.keySet())
{
System.out.println("Field: " + fieldName + " has value " + parsedJson.get(fieldName));
}

Parsing an array of objects


The code above will only work if the JSON string represents a simple object - we can tell it does because it starts with a curly bracket. However, if by chance the string contains an array of objects, the above code will throw an exception because the string cannot be parsed to a JSONObject instance. It needs to be converted to JSONArray instead:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class JSONAnalyzer
{
public static void main(String [] args)
{
String jsonString = args[0];
parse(jsonString);
}

public static void parse (Object obj)
{
if (obj instanceof JSONObject)
{
JSONObject object = (JSONObject)obj;
for (Object fieldName : object.keySet())
{
System.out.println("Field: " + fieldName + " has value " + object.get(fieldName));
}
}
else if (obj instanceof JSONArray)
{
JSONArray array = (JSONArray)obj;

for (int i = 0; i < array.size(); i++)
{
parse(array.get(i));
}
}
}
}
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems