Saturday, 1 November 2014

How to parse and create JSON string Android/Java

Use the package org.json.JSONObject, present in the android SDK.

Example:
  JSONObject j = new JSONObject();
  // values can be strings, booleans, ints and/or objects
  j.put("stringFieldName", "fieldValue");
  j.put("intFieldName", 42);
  // put throws an exception if any of the arguments is invalid.
  // if you're not sure about if what you're trying to write to JSON is null or not, you can use putOpt
  String nonNullField = "nonNullFieldName";
  String nullField = "nullFieldName";
  String thisIsAnArgumentAndImNotSureIfItWillBeNull = null;
  j.putOpt(nonNullField, "this is a non nul value");
  // nullField will not be added to the JSON
  j.putOpt(nullField, thisIsAnArgumentAndImNotSureIfItWillBeNull);

  String jsonString = j.toString();
  // jsonString is
  // {"nonNullFieldName":"this is a non nul value","intFieldName":42,"stringFieldName":"fieldValue"}
  // use JSONObject.toString(2) to return an indented JSON string with 2 spaces
  /*
   {
     "nonNullFieldName": "this is a non null value",
     "intFieldName": 42,
     "stringFieldName": "fieldValue"
   }
  */
 

You can created JSON trees by putting a JSONObject into another JSONObject
Parsing a JSON string is just as easy
  String jsonString = ...;//something like // {"nonNullFieldName":"this is a non null value","intFieldName":42,"stringFieldName":"fieldValue"}
  JSONObject j = new JSONObject(jsonString);
  // use the get methods to return the parsed values
  int intValue = j.getInt(...);
  String strValue = j.getString(...);


It's a little different if you're using pure java though
  JsonObject jb = Json.createObjectBuilder();
  jb.add("firstName", "Donald duck");
  jb.add("address", "Jupiter")
  jb.add("number", 42);
  
  // and here you have it!
  String jsonText = jb.toString();
  
More here