package com.misc.forum;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JsonParser {
public static void main(String[] args) {
String json1 = "[{\"name1\":\"value1\"},{\"name2\":\"value2\"},{\"name3\":\"value3\",\"name4\":\"value4\"}]" ;
String json2 = "[{\"id\":\"1\",\"delivery_id\":\"7\",\"subject\":\"this is test message number one\",\"created_on\":\"1279303283\",\"isread\":\"0\",\"summary\":\"Nam at metus sit amet massa ullamcorper tempus vitae a arcu. Sed pulvinar nunc vel dui porttitor vitae malesuada lorem tristique. Ut at ipsum nec lacus rutrum bibendum vitae quis tellus. Vestibulum a elit est, nec tristique metus. Nam ut neque a enim vest\"},{\"id\":\"2\",\"delivery_id\":\"8\",\"subject\":\"this is test message number two\",\"created_on\":\"1279303283\",\"isread\":\"0\",\"summary\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur quis suscipit purus. Aliquam erat volutpat. Vivamus iaculis semper ipsum vel commodo. In hac habitasse platea dictumst. Suspendisse potenti. Nullam ut est tortor. Sed accumsan felis a mass\"},{\"id\":\"3\",\"delivery_id\":\"9\",\"subject\":\"this is test message number three\",\"created_on\":\"1279303283\",\"isread\":\"0\",\"summary\":\"Nam at metus sit amet massa ullamcorper tempus vitae a arcu. Sed pulvinar nunc vel dui porttitor vitae malesuada lorem tristique. Ut at ipsum nec lacus rutrum bibendum vitae quis tellus. Vestibulum a elit est, nec tristique metus. Nam ut neque a enim vest\"},{\"id\":\"4\",\"delivery_id\":\"10\",\"subject\":\"this is test message number four\",\"created_on\":\"1273640400\",\"isread\":\"0\",\"summary\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur quis suscipit purus. Aliquam erat volutpat. Vivamus iaculis semper ipsum vel commodo. In hac habitasse platea dictumst. Suspendisse potenti. Nullam ut est tortor. Sed accumsan felis a mass\"}]" ;
List<Map<String,String>> parsedObjects = parseJsonString(json2) ;
System.out.println("Parsing complete, here are the objects:") ;
int count = parsedObjects.size() ;
System.out.println("Parsed JSON contained "+count+" objects") ;
for( Iterator<Map<String,String>> objIter = parsedObjects.iterator(); objIter.hasNext(); ) {
System.out.println("JSON Object:") ;
Map<String, String> objMap = objIter.next() ;
for( Iterator<String> keyIter = objMap.keySet().iterator(); keyIter.hasNext(); ) {
String key = keyIter.next() ;
String val = objMap.get(key) ;
System.out.println(" "+key+" = "+val) ;
}
}
}
public static List<Map<String,String>> parseJsonString(String str) {
List<Map<String,String>> result = new ArrayList<Map<String,String>>() ;
// Regexp to match multiple occurrences of {.....} separated by commas
Pattern pattern = Pattern.compile("(\\{.*?\\})((,\\{.*?\\}){0,})") ;
// To simplify code, check that string starts & ends with [] first
if( !str.startsWith("[") || !str.endsWith("]") ) {
System.out.println("JSON string doesn't start/end with []") ;
return result ;
}
// Middle bit between the [ ... ]
str = str.substring(1, str.length()-1) ;
Matcher matcher = pattern.matcher(str) ;
while( matcher != null && matcher.matches() ) {
String firstObj = matcher.group(1);
String restOfObjs = matcher.group(2);
System.out.println("firstObj = |"+firstObj+"|") ;
System.out.println("restOfObjs = |"+restOfObjs+"|") ;
Map<String,String> objMap = parseJsonObject(firstObj) ;
result.add(objMap) ;
// If the rest of the string isn't null, do regexp on it, skipping initial comma
if( restOfObjs != null && restOfObjs.length()>0 ) {
matcher = pattern.matcher(restOfObjs.substring(1)) ;
}
else {
matcher = null ;
}
}
return result ;
}
public static Map<String,String> parseJsonObject(String str) {
Map<String,String> result = new HashMap<String, String>() ;
Pattern pattern = Pattern.compile("(\".*?\":\".*?\")((,\".*?\":\".*?\"){0,})") ;
System.out.println("Parsing JSON object = |"+str+"|") ;
// Expect string to start/end with {} so check first to make parsing easier
if( !str.startsWith("{") || !str.endsWith("}") ) {
System.out.println("JSON object doesn't start/end with {}") ;
return result ;
}
str = str.substring(1, str.length()-1) ;
Matcher matcher = pattern.matcher(str) ;
while( matcher != null && matcher.matches() ) {
String firstNameValue = matcher.group(1);
String restOfNameValue = matcher.group(2);
System.out.println(" firstNameValue = |"+firstNameValue+"|") ;
System.out.println(" restOfNameValue = |"+restOfNameValue+"|") ;
addNameValueToMap(result,firstNameValue) ;
// If the rest of the string isn't null, do regexp on it, skipping initial comma
if( restOfNameValue != null && restOfNameValue.length()>0 ) {
matcher = pattern.matcher(restOfNameValue.substring(1)) ;
}
else {
matcher = null ;
}
}
return result ;
}
// Take a string of the form:
// "name1":"value1"
// Extract name part "name1", and value part "value1"
// Add them to the Map
public static void addNameValueToMap(Map<String,String> map, String nameValueStr) {
Pattern pattern = Pattern.compile("\"(.*?)\":\"(.*?)\"") ;
Matcher matcher = pattern.matcher(nameValueStr) ;
if( matcher.matches() ) {
String namePart = matcher.group(1) ;
String valPart = matcher.group(2) ;
map.put(namePart, valPart) ;
System.out.println(" Added name = |"+namePart+"|, value = |"+valPart+"|") ;
}
else {
System.out.println("name/Value pair is not expected syntax: |"+nameValueStr+"|") ;
}
}
}