I am new to parsing JSON in java. I have this JSON string:
[
{
"projectId":5,
"userName":"clinician",
"projectName":"r",
"projectSummary":"r",
"projectLanguage":"r",
"contactPersonName":"r",
"contactPersonCV":"r",
"contactPersonEmail":"r",
"contactPersonPhone":"r"
},
[
{
"consentFileId":2,
"projectId":5,
"consentDescription":"r",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":null
},
{
"consentFileId":3,
"projectId":5,
"consentDescription":"rrr",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":"localhost:8080/4c_viewFile?consentFileId=3"
}
],
[
{
"anonymized_patient_identifier":"r",
"projectId":5
},
{
"anonymized_patient_identifier":"2",
"projectId":5
},
{
"anonymized_patient_identifier":"5",
"projectId":5
}
]
]
I have managed to get values from simpler JSON strings but this one has multiple levels and also there is no key in each level. I tried with simple code like this:
Object obj = parser.parse(data);
JSONObject jsonObject = (JSONObject) obj;
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
but I get the error [java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject] And also I don't understand how I will get the values in lower level without a key. I tried also to save it as a JSONArray but it didn't work.
your root of json is type of JSONArray,
the first object stored in the root array is an object, you can retrieve it by using index = 0 .
this is a hack to make your code work:
JSONArray jsonArray = JSONArray.fromObject(data);
JSONObject jsonObject=obj.getJSONObject(0);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
NOTE:
to convert a String to JSONArray, you can do :
JSONArray array = JSONArray.fromObject(data);
To improve on nafas answer, I would do this to see all the objects in the array:
Object obj = parser.parse(data);
JSONArray jsonArray = (JSONArray) obj;
for (int i = 0; i < jsonArray.size (); i++) {
JSONObject jsonObject=obj.getJSONObject(i);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
}
Related
I am given a JSON that will come in this format:
"template":{
"mod1":[
{
"param1":"55",
"param2":"5",
"param3":"somedata"
}
],
"mod2":[
{
"param1":"somedata",
"param2":"somedata"
}
],
"mod3":[
{
"param1":"somedata",
"param2":"somedata",
"param3":"somedata"
}
],
"mod4":[
{
"param1":"somedata",
"param2":"somedata"
}
],
"mod5":[
{
"param1":"somedata"
}
]
}
}
What is the easiest way to parse it? What I'd like is to get the params inside the mod and their associated values together, to store into a database. The way I am doing it is as so:
JSONObject obj = new JSONObject(json);
System.out.println(obj);
Iterator<String> keys = obj.keys();
while(keys.hasNext()) {
String key = keys.next();
JSONObject currTemplate = (JSONObject) obj.get(key);
if(currTemplate instanceof JSONObject) {
System.out.println("LIST OF ALL MODULES : " + currTemplate);
Iterator<String> currObjKeys = ((JSONObject) currTemplate).keys();
while(currObjKeys.hasNext()) {
String currObjKey = currObjKeys.next();
System.out.println("MODULE: " + currObjKey);
JSONArray array = currTemplate.getJSONArray(currObjKey);
System.out.println("ARRAY: " + array);
for(int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
String[] names = JSONObject.getNames(object);
for(String name: names) {
System.out.println("PARAMS");
System.out.println(name);
System.out.println(object.get(name));
}
}
}
}
And it currently prints what I need correctly. What I am asking is if there is a more efficient way to do it - the way I currently have it is O(N^4), and I was wondering if anyone had any idea to parse the JSON in a more efficient way. Note: the params will not always be in form param1, param2, the names will always be different. Just changed it for confidentiality sake.
Thank you in advance.
I am using the json-simple-1.1.jar
and trying to get multiple (atleast 3) values from the json as shown in the code section.
My code works for a JSON with multiple arrays but not working for simple json format.
{
"Addresses": {
"UserName": "Rahul",
"Status": "Active",
"CreateDate": "2017-01-09T11:39:31.244Z",
"SecretAccessKey": "ABCD-EFGH-HIJK",
"AccessKeyId": "1234567"
}
}
Following is the java logic I am trying to use:
public static String[] getValuesFromJson(String filename, Object key, int exp_sizeOfArray, String[] exp_keys) throws FileNotFoundException, IOException, ParseException {
String valuesFromJson[] = new String[exp_keys.length];
/** Create a JSONParser object*/
JSONParser parser = new JSONParser();
/** Read the JSON file using parser*/
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(
filename));
System.out.println("JsonObject size: "+jsonObject.keySet().size());
for (Object object : jsonObject.keySet()) {
System.out.println(jsonObject.get(object.toString()));
}
/** Get the values in JSONArray using the key*/
JSONArray jsonArray = (JSONArray) jsonObject.get(key);
for (int i = 0; i < jsonArray.size(); i++) {
/** Add the individual set from JSONArray to a JSONObject */
JSONObject subJsonObject = (JSONObject) parser.parse(jsonArray.get(i).toString());
/** Check for expected size of array */
if(subJsonObject.size() <= exp_sizeOfArray){
int index=0;
/** Check for each key value in the sub-JSONObject keySet*/
for (Object object : subJsonObject.keySet()) {
/** Iterate until the expected key value matches with the actual value*/
for (int j = 0; j < exp_keys.length; j++) {
/** Check if the expected key matches with any of the key value*/
if(object.toString().trim().equals(exp_keys[j].toString().trim())){
System.out.println("Key: '".concat(object.toString()).concat("'\tValue: '").concat(subJsonObject.get(object)+"'"));
valuesFromJson[index] = subJsonObject.get(exp_keys[j]).toString();
index++;
break;
}
}
}
}
}
/** Return the value of expected key*/
return valuesFromJson;
}
I am getting error: "org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray" on below line:
JSONArray jsonArray = (JSONArray) jsonObject.get(key);
You are trying to cast JSONObject to JSONArray, but there is no array. Rather get all object keys and iterate over it.
If you go to json.org(1) you can find there:
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma)
Voila!
Done it without converting JSONObject to JSONArray
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(
filename));
/** Creating another JSONObject here */
JSONObject jsonObject2 = (JSONObject) parser.parse(jsonObject.get(key).toString());
for (Object newKey : jsonObject2.keySet()) {
System.out.println("Key: '".concat(newKey.toString()).concat("'\tValue: '").concat(jsonObject2.get(newKey)+"'"));
}
Thank you guys for the help!
i'm trying to parse this JSON code
{
"resultCode":"350",
"message":"OK",
"result":1,
"data":
{
"totalCount":"2",
"videos":[
{
"videoId":"73bfedf534",
"VideoUrl":"www.videourlexample.com",
"title":"vbsample1",
"description":""
},
{
"videoId":"73bfedf534",
"VideoUrl":"www.videourlexample.com",
"title":"vbsample2",
"description":""
}
]
}
}
I was able to parse only this.
"resultCode":"350",
"message":"OK",
"result":1,
this is the java code
JSONObject jsonObject = (JSONObject)
//return the JSON code above.
jsonParser.parse(getHTML("...httpRequest..."));
// get a String from the JSON object
String resultCode = (String) jsonObject.get("resultCode");
System.out.println("[RESULTCODE] The message is: " + resultCode);
// get a String from the JSON object
String message = (String) jsonObject.get("message");
System.out.println("[MESSAGE] The message is: " + message);
// get a number from the JSON object
long result = (long) jsonObject.get("result");
System.out.println("[RESULT] The resultCode is: " + result);
I can't parse the "data". Someone can help me?
I would like to take each value from the json array separately... like resultCode, message and result.
Thank you.
JSONObject mainObj= new JSONObject(yourJSON);
String resultCode= mainObj.get("resultCode");
String message= mainObj.get("message");
String result= mainObj.get("result");
JSONObject dataObj = mainObj.get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
JSONObject obj= jsonArray.get(i);
String videoId=obj.get("videoId");
String videoUrl=obj.get("VideoUrl");
String title=obj.get("title");
String description=obj.get("description");
System.out.println("videoId="+videoId +"videoUrl="+videoUrl+"title=title"+"description="+description);
}
System.out.println("resultCode"+resultCode+"message"+message+"result"+result);
You can try using this:-
JSONObject dataObj = (JSONObject)dataObj .get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
System.out.println(((JSONObject)jsonArray.get(i)).get("videoUrl"));
}
Currently I have just printes videoUrl, you can similarly get other attributes for videos.
for data use:
int totalCount = (int) ((Map) jsonObject.get("data")).get("totalCount");
JSONArray videos = (JSONArray) jsonObject.get("data")).get("videos");
and then parse videos JSONArray.
How can I parse in Android a Json array of strings and save it in a java string array ( like: xy[ ] ) ?
My Json to be parsed :
[
{
"streets": [ "street1", "street2", "street3",... ],
}
]
Later in my code I want to populated with that array a spinner item in my layout.
Everything i tried enden with only one street item listed in the spinner.
To parse
try {
JSONArray jr = new JSONArray("Your json string");
JSONObject jb = (JSONObject)jr.getJSONObject(0);
JSONArray st = jb.getJSONArray("streets");
for(int i=0;i<st.length();i++)
{
String street = st.getString(i);
Log.i("..........",""+street);
// loop and add it to array or arraylist
}
}catch(Exception e)
{
e.printStackTrace();
}
Once you parse and add it to array. Use the same to populate your spinner.
[ represents json array node
{ represents json object node
Try this..
JSONArray arr = new JSONArray(json string);
for(int i = 0; i < arr.length(); i++){
JSONObject c = arr.getJSONObject(i);
JSONArray ar_in = c.getJSONArray("streets");
for(int j = 0; j < ar_in.length(); j++){
Log.v("result--", ar_in.getString(j));
}
}
We need to make JSON object first. For example,
JSONObject jsonObject = new JSONObject(resp);
// resp is your JSON string
JSONArray arr = jsonObject.getJSONArray("results");
Log.i(LOG, "arr length = " + arr.length());
for(int i=0;i<arr.length();i++)
{...
arr may contains other JSON Objects or JSON array. How to convert the JSON depends on the String. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling
I have a json of following format:
{
"Result": {
"question": "Barack Obama vs Mitt Romney?",
"option": [
"Barack Obama",
"Mitt Romney",
"Other"
],
"percentage": [
20,
40,
80
]
}
}
and I am using following code to parse it but this giving null pointer exception at option array.
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONObjectFromUrl(url);
Log.e("json",json.toString());
Log.e("-------url-------", ""+url);
String resultStr = json.getString("Result");
Log.e("result string ",resultStr);
JSONObject jsonObject2 = new JSONObject(resultStr);
String question_string = jsonObject2.getString("question");
Log.e("question String ",question_string);
String option_str = jsonObject2.getString("option");
JSONArray optionArray = new JSONArray(option_str);
Log.d("option array", String.valueOf(optionArray.length()));
You need to get the json array this way:
JSONArray optionArray = jsonObject2.getJSONArray("option");
Log.d("option array", String.valueOf(optionArray.length()));
check http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Use:
JSONArray optionArray = jsonObject2.getJSONArray("option");
as "option" key points to an array and not to a String.
You're going way too complicated here, and not using those lovely GetJSONObject and getJSONArray functions, which will cause you to double parse a lot. Try this
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONObjectFromUrl(url);
Log.e("json",json.toString());
Log.e("-------url-------", ""+url);
JSONObject jsonObject2 = json.getJSONObject("Result");
String question_string = jsonObject2.getString("question");
Log.e("question String ",question_string);
JSONArray optionArray = jsonObject2.getJSONArray("option");
Instead of using
String option_str = jsonObject2.getString("option");
use this :
JSONARRAY optionArray = jsonObject2.getJSONAray("option");
for(int i=0;i<optionArray.length; i++){
String option = optionArray[i].getString();}
Try this..