how to parse a JSON string which is inside a array - java

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..

Related

JsonObject by default adding backslash to json string

I have list of items adding in to JsonArray and convert this JsonArray to string and adding this string JsonObject as a property. But While I am getting response is with back slashs.
jsonObject.addProperty("name",rsmd.getColumnLabel(1));
JsonArray itemJsonArray = new JsonArray();
JsonArray jsonArray = new JsonArray();
while (resultSet.next()) {
itemJsonArray.add(resultSet.getString(1));
}
jsonObject.addProperty("items",itemJsonArray.toString());
jsonArray.add(jsonObject);
Output:
{
"name": "username",
"items": [\"Mohan\",\"Mohan\",\"Mohan\"]
}
Basically your problem is you are doing itemJsonArray.toString() and also you need to use add() instead of addProperty(), so:
Instead of
jsonObject.addProperty("items",itemJsonArray.toString());
Do this:
jsonObject.add("items",itemJsonArray);

Removing backslash from JSON format while programmatically constructing a JSON array

I want to parse the JSON data by removing the backslash from the JSON format.
I have tried removing the backslash from the JSON format by the following code but nothing worked out
JSONArray packsJSON = new JSONArray();
JsonObject innerObject;
for(PackageList packageList:selecteditem)
{
innerObject=new JsonObject();
innerObject.addProperty("pack_id",packageList.getSubs_id());
innerObject.addProperty("pack_dsc", packageList.getSubs_desc());
innerObject.addProperty("pack_tax_amt", packageList.getTax_amnt());
innerObject.addProperty("pack_grand_total", packageList.getSubs_grnd_tot_prc());
Log.i("INNEROBJECT","hyu"+innerObject);
packsJSON.put(innerObject);
Log.i("PACKJSON","nkd==>>"+packsJSON)
}
output of INNEROBJECT:
{"pack_id":"39","pack_dsc":"350 Package","pack_tax_amt":"0","pack_grand_total":"419"}
The output of PACKJSON:
[ "{\"pack_id\":\"39\",\"pack_dsc\":\"350 Package\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"419\"}",
"{\"pack_id\":\"2232\",\"pack_dsc\":\"Bangara(280)\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"280\"}"
]
[
"{"pack_id":"39","pack_dsc":"350 Package","pack_tax_amt":"0","pack_grand_total":"419"}",
"{"pack_id":"2232","pack_dsc":"Bangara(280)","pack_tax_amt":"0","pack_grand_total":"280"}"
]
Your JSONArray is of org.json package and JsonObject is of com.google.gson package
so your innerObject's type should be org.json.JSONObject
JSONArray packsJSON = new JSONArray();
JSONObject innerObject;
for(PackageList packageList:selecteditem)
{
innerObject=new JSONObject();
innerObject.put("pack_id",packageList.getSubs_id());
innerObject.put("pack_dsc", packageList.getSubs_desc());
innerObject.put("pack_tax_amt", packageList.getTax_amnt());
innerObject.put("pack_grand_total", packageList.getSubs_grnd_tot_prc());
Log.i("INNEROBJECT","hyu"+innerObject);
packsJSON.put(innerObject);
Log.i("PACKJSON","nkd==>>"+packsJSON)
}
Please check below answer.
String jsonString = "[ "{\"pack_id\":\"39\",\"pack_dsc\":\"350 Package\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"419\"}","{\"pack_id\":\"2232\",\"pack_dsc\":\"Bangara(280)\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"280\"}"]"
String outputString = jsonString.replaceAll("\\\\", "");
Log.e("Clear String :", outputString);
OUTPUT

Parse JSON string in Java without keys

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");
}

Android json parsing without array name

I have a Json Array as string without name and I want to parse it how can i do it in android ?
My array :
{"emp_info":[
{"id":"1","groupe":"1","professeur":"1"},
{"id":"2","groupe":"2","professeur":"1"}
]}
This is how you can parse it
Assuming your json string is data
JSONObject jsonObj = new JSONObject(data);
JSONArray empInfo = jsonObj.getJSONArray("emp_info");
for(int i = 0; i < empInfo.length(); i++){
JSONObject obj = empInfo.getJSONObject(i);
String id = obj.getString("id");
String groupe = obj.getString("groupe");
String professeur = obj.getString("professeur");
}
The example json you gave has a name, but if it doesn't this is how I do it. Using Gson to parse JSON, I use TypeToken to tell the gson builder it's an array.
List<MyObject> jsonObject = new Gson().fromJson(json, new TypeToken<List<MyObject>>().getType());
With the following code you'll have an object representation of your json array.

JSON parse Android - object in object

How to parse this json? I want get data from title, field_place and brothers fields.
{
"events": [
{
"event": {
"title": "BITUMIX Martyna Jastrz\u0119bska",
"field_place": "Nowe Miejsce Al Jerozolimskie 51 lok.2",
"field_zdjecie": "http:\/\/wybierzkulture.waw.pl\/sites\/default\/files\/styles\/post\/public\/martyna_jastrzebska_bitumix_2.jpg?itok=nd2O5U5z"
}
},
{
"event": {
"title": "Wiecz\u00f3r Komedii Improwizowanej - D\u017cem Impro!",
"field_place": "",
"field_zdjecie": "http:\/\/wybierzkulture.waw.pl\/sites\/default\/files\/styles\/post\/public\/dzem_17_maja.jpg?itok=bfgDYxKq"
}
},
...
I tried:
JSONObject itemm = jArray.getJSONObject(i);
JSONObject oneObject = itemm.getJSONObject("event");
String title = oneObject.getString("title");
String field_place = oneObject.getString("field_place");
... but it doesn't work.
In a JSON string , there are two symbols that guide you through parsing :
{ - indicates a JSONObject
[ - indicates a JSONArray
When parsing a json string, you should go through this items iteratively. To understand how many JsonObjects and JsonArrays you have in your string , and from which you should start parsing, use a json-visualizer tool like this website. :
Example : As you see, the root object is a JSONObject which consists of an JSONArray with three jsonOnjects. To parse such a structure you can use :
JSONObject jsonobj = new JSONObject(jsonstring);
String result = jsonObject.getString("success");
String error_number = jsonObject.getString("error_number");
String error_message = jsonObject.getString("error_message");
JSON Array jsonarray = jsonobj.getJSONArray();
String[] names = new String[jsonArray.length()];
String[] formattedNames = new String[jsonArray.length()];
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
names [i] = jsonObject.getString("name");
formattedNames [i] = jsonObject.getString("formattedName");
}
try this
JSONArray element = jsonobj.getJSONArray("events");
for(int i=0;i < element.length();i++){
JSONObject e = element.getJSONObject(i);
Log.d("TESTTT22",e.getJSONObject("event").getString("title"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources