Skip to content

Instantly share code, notes, and snippets.

@kiran-machhewar
Created June 27, 2018 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiran-machhewar/ad26033d7e710c9efa78e2325f6b16a8 to your computer and use it in GitHub Desktop.
Save kiran-machhewar/ad26033d7e710c9efa78e2325f6b16a8 to your computer and use it in GitHub Desktop.
JSONObject
/**
* @ApexClass : JSONObject
* @Author : Kiran Machhewar
* @Description : This class can be used to parse and work with json data in apex easy.
*/
public class JSONObject {
public String jsonString; //to hold the json string
private Object jsonObject; //to hold the deserialized json data
public JSONObject(String jsonString) {
this.jsonString = jsonString;
this.jsonObject = JSON.deserializeUntyped(jsonString);
}
private JSONObject(Object jsonObject){
this.jsonObject = jsonObject;
}
private JSONObject(){
this.jsonObject = null;
}
/**
* This method will give the JSONObject on which other methods could be called
*/
public JSONObject get(String field){
if(jsonObject != null){
Map<String,Object> jsonObjectMap = (Map<String,Object>)jsonObject;
return new JSONObject(jsonObjectMap.get(field));
}else{
return new JSONObject();
}
}
/**
* This method will give the JSONObject on which other methods could be called
*/
public List<JSONObject> getArray(String field){
List<JSONObject> jsonObjects = new List<JSONObject>();
List<Object> objects = (List<Object>)((Map<String,Object>)jsonObject).get(field);
for(Object theObject : objects){
jsonObjects.add(new JSONObject(theObject));
}
return jsonObjects;
}
public List<JSONObject> getArray(){
List<JSONObject> jsonObjects = new List<JSONObject>();
List<Object> objects = (List<Object>)jsonObject;
for(Object theObject : objects){
jsonObjects.add(new JSONObject(theObject));
}
return jsonObjects;
}
public override String toString(){
return (jsonObject == null)? null : (''+jsonObject);
}
public Object value(){
return jsonObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment