Parson JSON


Last Updated:

  1. andywhoa

    andywhoa Well-Known Member This Topic's Starter

    Joined:
    May 15, 2010
    Messages:
    105
    Likes Received:
    13
    Could someone point me to a good example for parsing JSON without using GSON?

    My JSON string looks like this
    [{"name":"value"},{"name":"value"},{"name":"value"}]

    I can easily parse if theres just one bracket, but when there are multiple (in this case 3), I'm looking for a good way to do it


    Thanks
     

    Advertisement
  2. markb

    markb Well-Known Member

    Joined:
    Sep 14, 2009
    Messages:
    148
    Likes Received:
    26
    Are you after a generic JSON parser, or do you just want to parse strings like the example you've given?
     
  3. andywhoa

    andywhoa Well-Known Member This Topic's Starter

    Joined:
    May 15, 2010
    Messages:
    105
    Likes Received:
    13
    I actually gave you a bad example.

    I'm looking for how to use the JSON objects to parse the message. Here is the exact message I'm looking to parse:

    Code (Text):
    1. [{"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"},{"id":"5","delivery_id":"11","subject":"this is test message number five","created_on":"1275368400","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":"6","delivery_id":"12","subject":"this is test message number six","created_on":"1277442000","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"}]
     
  4. markb

    markb Well-Known Member

    Joined:
    Sep 14, 2009
    Messages:
    148
    Likes Received:
    26
    Here you go...

    Code (Text):
    1.  
    2. package com.misc.forum;
    3.  
    4. import java.util.ArrayList;
    5. import java.util.HashMap;
    6. import java.util.Iterator;
    7. import java.util.List;
    8. import java.util.Map;
    9.  
    10. import java.util.regex.Matcher;
    11. import java.util.regex.Pattern;
    12.  
    13. public class JsonParser {
    14.     public static void main(String[] args) {
    15.         String json1 = "[{\"name1\":\"value1\"},{\"name2\":\"value2\"},{\"name3\":\"value3\",\"name4\":\"value4\"}]" ;
    16.         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\"}]" ;
    17.  
    18.         List<Map<String,String>> parsedObjects = parseJsonString(json2) ;
    19.  
    20.         System.out.println("Parsing complete, here are the objects:") ;
    21.        
    22.         int count = parsedObjects.size() ;
    23.         System.out.println("Parsed JSON contained "+count+" objects") ;
    24.         for( Iterator<Map<String,String>> objIter = parsedObjects.iterator(); objIter.hasNext(); ) {
    25.            
    26.             System.out.println("JSON Object:") ;
    27.  
    28.             Map<String, String> objMap = objIter.next() ;
    29.            
    30.             for( Iterator<String> keyIter = objMap.keySet().iterator(); keyIter.hasNext(); ) {
    31.                 String key = keyIter.next() ;
    32.                 String val = objMap.get(key) ;
    33.                
    34.                 System.out.println("  "+key+" = "+val) ;
    35.             }
    36.         }
    37.     }
    38.    
    39.     public static List<Map<String,String>> parseJsonString(String str) {
    40.         List<Map<String,String>> result = new ArrayList<Map<String,String>>() ;
    41.        
    42.         // Regexp to match multiple occurrences of {.....} separated by commas
    43.         Pattern pattern = Pattern.compile("(\\{.*?\\})((,\\{.*?\\}){0,})") ;
    44.        
    45.         // To simplify code, check that string starts & ends with [] first
    46.         if( !str.startsWith("[") || !str.endsWith("]") ) {
    47.             System.out.println("JSON string doesn't start/end with []") ;
    48.             return result ;
    49.         }
    50.        
    51.         // Middle bit between the [ ... ]
    52.         str = str.substring(1, str.length()-1) ;
    53.        
    54.         Matcher matcher = pattern.matcher(str) ;
    55.         while( matcher != null && matcher.matches() ) {
    56.             String firstObj   = matcher.group(1);
    57.             String restOfObjs = matcher.group(2);
    58.            
    59.             System.out.println("firstObj    = |"+firstObj+"|") ;
    60.             System.out.println("restOfObjs  = |"+restOfObjs+"|") ;
    61.            
    62.             Map<String,String> objMap = parseJsonObject(firstObj) ;
    63.             result.add(objMap) ;
    64.            
    65.             // If the rest of the string isn't null, do regexp on it, skipping initial comma
    66.             if( restOfObjs != null && restOfObjs.length()>0 ) {
    67.                 matcher = pattern.matcher(restOfObjs.substring(1)) ;
    68.             }
    69.             else {
    70.                 matcher = null ;
    71.             }
    72.         }
    73.        
    74.         return result ;
    75.     }
    76.    
    77.     public static Map<String,String> parseJsonObject(String str) {
    78.         Map<String,String> result = new HashMap<String, String>() ;
    79.        
    80.         Pattern pattern = Pattern.compile("(\".*?\":\".*?\")((,\".*?\":\".*?\"){0,})") ;
    81.        
    82.         System.out.println("Parsing JSON object = |"+str+"|") ;
    83.        
    84.         // Expect string to start/end with {} so check first to make parsing easier
    85.         if( !str.startsWith("{") || !str.endsWith("}") ) {
    86.             System.out.println("JSON object doesn't start/end with {}") ;
    87.             return result ;
    88.         }
    89.        
    90.         str = str.substring(1, str.length()-1) ;
    91.  
    92.         Matcher matcher = pattern.matcher(str) ;
    93.         while( matcher != null && matcher.matches() ) {
    94.             String firstNameValue  = matcher.group(1);
    95.             String restOfNameValue = matcher.group(2);
    96.            
    97.             System.out.println("  firstNameValue   = |"+firstNameValue+"|") ;
    98.             System.out.println("  restOfNameValue  = |"+restOfNameValue+"|") ;
    99.            
    100.             addNameValueToMap(result,firstNameValue) ;
    101.                        
    102.             // If the rest of the string isn't null, do regexp on it, skipping initial comma
    103.             if( restOfNameValue != null && restOfNameValue.length()>0 ) {
    104.                 matcher = pattern.matcher(restOfNameValue.substring(1)) ;
    105.             }
    106.             else {
    107.                 matcher = null ;
    108.             }
    109.         }
    110.  
    111.         return result ;
    112.     }
    113.    
    114.     // Take a string of the form:
    115.     //    "name1":"value1"
    116.     // Extract name part "name1", and value part "value1"
    117.     // Add them to the Map
    118.    
    119.     public static void addNameValueToMap(Map<String,String> map, String nameValueStr) {
    120.         Pattern pattern = Pattern.compile("\"(.*?)\":\"(.*?)\"") ;
    121.         Matcher matcher = pattern.matcher(nameValueStr) ;
    122.        
    123.         if( matcher.matches() ) {
    124.             String namePart = matcher.group(1) ;
    125.             String valPart  = matcher.group(2) ;
    126.            
    127.             map.put(namePart, valPart) ;
    128.             System.out.println("    Added name = |"+namePart+"|, value = |"+valPart+"|") ;
    129.         }
    130.         else {
    131.             System.out.println("name/Value pair is not expected syntax: |"+nameValueStr+"|") ;
    132.         }
    133.     }
    134. }
    135.  
    136.  
    I knocked it up quite quickly, so it might not be the most elegant code.
    It's not organised into a reusable class, but that should be easy enough to fix.
    The pattern compilation only really needs to be done once for each regexp so those could be moved out and stored as constants.

    If you run that with my simple test string json1, which is effectively:
    Code (Text):
    1.  
    2. [{"name1":"value1"},{"name2":"value2"},{"name3":"value3","name4":"value4"}]
    3.  
    It dumps out this output:

    Code (Text):
    1.  
    2. Parsing complete, here are the objects:
    3. Parsed JSON contained 3 objects
    4. JSON Object:
    5.   name1 = value1
    6. JSON Object:
    7.   name2 = value2
    8. JSON Object:
    9.   name3 = value3
    10.   name4 = value4
    11.  
    The parseJsonString method returns a list, with one entry for each JSON object.
    (Each thing in curly brackets counts as one object: [ {object-1},{object-2}, etc..])

    Each list entry is a Map where the key is a string and the value is a string.
    The name/value pairs within an object get turned into a Map.
    So "name1":"value1","name2":"value2" becomes 2 entries in the map, one with key "name1" and value "value1", and one with key "name2" and value "value2".


    If you run it with the other test string json2, which is the beginning of your example:

    Code (Text):
    1.  
    2. Parsing complete, here are the objects:
    3. Parsed JSON contained 4 objects
    4. JSON Object:
    5.   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
    6.   delivery_id = 7
    7.   created_on = 1279303283
    8.   subject = this is test message number one
    9.   id = 1
    10.   isread = 0
    11. JSON Object:
    12.   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
    13.   delivery_id = 8
    14.   created_on = 1279303283
    15.   subject = this is test message number two
    16.   id = 2
    17.   isread = 0
    18. JSON Object:
    19.   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
    20.   delivery_id = 9
    21.   created_on = 1279303283
    22.   subject = this is test message number three
    23.   id = 3
    24.   isread = 0
    25. JSON Object:
    26.   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
    27.   delivery_id = 10
    28.   created_on = 1273640400
    29.   subject = this is test message number four
    30.   id = 4
    31.   isread = 0
    32.  
    I would have run it with the whole of your example, but I got fed up of typing the escape characters in front of all the quotes. (And the line of code was getting huge. Too huge to post here.)

    If you're not familiar with regular expressions then it might not be obvious how it works.
    It's not helped by using [ ] { } " characters in the JSON string, which are all special characters in regular expressions, so need to be escaped.

    The code works with the syntax you used in your example.
    If your syntax ends up being different then you'll obviously have to change things.
    (e.g. if you're expecting arbitrary whitespace between things, you'll have to cope with that.)

    There aren't a lot of comments in the code. Sorry about that. I'd do more but it's late here. (00:25 UK time)

    I'll try to help out with explanations if you need them. But maybe not right now.

    Mark

    p.s.
    If you now decide that you really wanted a totally generic parser after all, then this won't be of any use to you. (And I'll have wasted an hour.)
     
    Yathushan and andywhoa like this.
  5. andywhoa

    andywhoa Well-Known Member This Topic's Starter

    Joined:
    May 15, 2010
    Messages:
    105
    Likes Received:
    13
    Man, I feel so bad, lol. I wrote a little bit of code that split out the JSON to something the JSONObject could understand.

    The JSONObject can parse the following two types of JSON strings:
    1) {"name":"value"},{"name":"value"},{"name":"value"}
    2) {"name":"value","name":"value","name":"value"}

    But it can't correctly parse a hybrid of the two:
    {"name":"value","name":"value"},{"name":"value","name":"value"}

    So what I did was split the overall JSON into a String array of smaller JSON strings like so:

    Code (Text):
    1.         try{
    2.             // if there are beginning and ending
    3.             // square brackets, be gone with them
    4.             if(json.startsWith("[")) {
    5.                 json = json.substring(1);
    6.             }
    7.             if(json.endsWith("]")) {
    8.                 json = json.substring(0, json.length()-2);
    9.             }
    10.            
    11.             // parse the entire collection into smaller json strings
    12.             String [] sarray = json.split("\\},\\{");
    13.            
    14.             // go through each one and get the data
    15.             for(int i=0; i<sarray.length; i++) {
    16.                 String jsub = sarray[i];
    17.                 if(!jsub.startsWith("{")) {
    18.                     jsub = "{" + jsub;
    19.                 }
    20.                 if(!jsub.endsWith("}")) {
    21.                     jsub = jsub + "}";
    22.                 }
    23.                 JSONObject jo = new JSONObject(jsub);
    24.                 JSONArray jn = jo.names();
    25.                 JSONArray jv = jo.toJSONArray(jn);
    26.                
    27.                 for(int x=0; x<jn.length(); x++) {
    28.                     String name = jn.getString(x);
    29.                     String value = jv.getString(x);
    30.                 }
    31.             }
    32.  
    33.         }
    34.         catch(JSONException e) {
    35.             Log.e("json", e.toString());
    36.         }
     
  6. markb

    markb Well-Known Member

    Joined:
    Sep 14, 2009
    Messages:
    148
    Likes Received:
    26
    Yeah, that'll do it too. :)

    I wasn't aware of the JSONObject class. I should have googled first.

    Mark
     

Share This Page

Loading...