JSON parse Android - object in object - java

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

Related

How can I extract a specific part of a JSON file?

This is my JSON file :
{
"coord":{
"lon":139,
"lat":35
},
"weather":[
{
"id":803,
"main":"Clouds",
"description":"broken clouds",
"icon":"https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F04n.png?1499366020983"
}
],
"base":"stations",
"main":{
"temp":7,
"pressure":1025,
"humidity":75,
"temp_min":7,
"temp_max":7
},
"visibility":10000,
"wind":{
"speed":5.1,
"deg":100
},
"clouds":{
"all":75
},
"dt":1549794600,
"sys":{
"type":1,
"id":8024,
"message":0.0034,
"country":"JP",
"sunrise":1549748122,
"sunset":1549786891
},
"id":1851632,
"name":"Shuzenji",
"cod":200
}
I have tried to extract the weather array but it doesn't work.
JSONArray mArray;
try {
mArray = new JSONArray(result);
for (int i = 0; i < mArray.length(); i++) {
JSONObject mJsonObject = mArray.getJSONObject(i);
txtJson.append(mJsonObject.getString("weather"));
}
} catch (JSONException e) {
e.printStackTrace();
//txtJson.setText(result);
}
txtJson.setText(result);
}
I don't know what you expect that code to do, but if you want to extract the weather array, this is how you do it.
JSONObject json = new JSONObject(result);
JSONArray weather = json.getJSONArray("weather");
Then you can get individual entries in the array
JSONObject entry = weather.getJSONObject(0);
int id = entry.getInt("id");
String main = entry.getString("main");
or if you just want to turn the array back to a string
String s = weather.toString();

how to get highlight term in the json result and save in into list? java

{
"relevant": ["Lighthouse", "family", "house", "national Ranking", "national Years", "national Selection", "carbohydrate", "national Affiliation", "home Arena", "temp Place"],
"result": [{
"keyword": "And thank people mission American Homeland Department Security White Applause",
"Sentence": "At the White House he has done an outstanding job.",
"highlightTerm": ["house"]
}, {
"keyword": "And thank people mission American Homeland Department Security White Applause",
"Sentence": "Welcome to the White House and welcome to this historic moment.",
"highlightTerm": ["house","family"]
}]
}
I would like to parser the JSON result to get all the highlightTerm and save it into ArrayList.
as the "highlightTerm": ["house","family"] is not a string, how to parse it???
JSONArray result = jsonObject.getJSONArray("result");
System.out.println("result is:: " + result);
ArrayList<String> highlightTermlist = new ArrayList<String>();
for (int i =0; i < result.length(); i++){
// String Sentence = result.getJSONObject(i).getString("Sentence");
JSONObject j = result.getJSONObject(i);
System.out.println("jjjjjjjjjjjjjjjjjjjjjjjjjjjj:: " + j);
error:
ArrayList<String> highlightTermlist =result.getJSONObject(i).getArrayList("highlightTermlist");
You have get as a Json Array and loop through it.
Try with the below code.. it gives result as
Complete HighlightTerms list --[family, house]
converting the list to Json Object with JsonArray element, as below.
{"highlightTerm":["house","house","family"]}
If you want duplicate values as well, change from Set to list.
JSONParser parser = new JSONParser();
List<String> allHighlightItems = new ArrayList<>();
try {
Object obj = parser.parse(new FileReader(
"sample.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray results = (JSONArray)(jsonObject.get("result"));
System.out.println("Complete Data list --"+results.toString());
for(Object singleResult : results) {
JSONObject singleArrayData = (JSONObject) singleResult;
JSONArray highlightTermOfGivenResult = (JSONArray)singleArrayData.get("highlightTerm");
for(Object singleHighlightTerm: highlightTermOfGivenResult){
if(singleHighlightTerm != null) {
allHighlightItems.add(singleHighlightTerm.toString());
}
}
}
System.out.println("Complete HighlightTerms list --"+allHighlightItems.toString());
JSONObject myJsonObject = new JSONObject();
myJsonObject.put("highlightTerm",allHighlightItems);
System.out.println("Complete HighlightTerms list --"+myJsonObject.toString());
} catch (Exception e) {
e.printStackTrace();
}

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

get data from Json array in Json array Android Java

Hello how to get data from Json Array in another Json array i have get data till attachments but attachment doesnt work, All code work till attachments how to get data from attachments I need to get "photo_75" from it
Json
"response":{
"count":3,
"items":[
{
"id":3,
"from_id":205110032,
"owner_id":-81865402,
"date":1417672154,
"post_type":"post",
"text":"jjjjASDFGHJKYTRDXCVB",
"attachments":[
{
"type":"photo",
"photo":{
"id":330414711,
"album_id":-7,
"owner_id":205110032,
"photo_75":"http:\/\/cs605116.vk.me\/v605116032\/6325\/3SwTo8j4lJ0.jpg",
"photo_130":"http:\/\/cs605116.vk.me\/v605116032\/6326\/_OZA86FO3Nw.jpg",
"photo_604":"http:\/\/cs605116.vk.me\/v605116032\/6327\/AUtB59708Nw.jpg",
"photo_807":"http:\/\/cs605116.vk.me\/v605116032\/6328\/59oAdfz9jgI.jpg",
"width":538,
"height":807,
"text":"",
"date":1399134687,
"access_key":"7297eb663de2e4e6b2"
}
}
],
"comments":{
"count":0
},
"likes":{
"count":0
},
"reposts":{
"count":0
}
},
Java
private void parseJsonFeed(JSONObject response) {
try {
JSONObject parent = response.getJSONObject("response");
JSONArray feedArray = parent.getJSONArray("items");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("post_type"));
item.setTimeStamp(feedObj.getString("date"));
// Image might be null sometimes
String image = feedObj.isNull("photo") ? null : feedObj
.getString("photo");
item.setImge(image);
item.setStatus(feedObj.getString("text"));
All code work till there how to get data from attachments
***JSONObject response1 = response.getJSONObject("response");
feedArray = parent.getJSONArray("items");***
JSONArray feedArray1 = response1.getJSONArray("attachments");
for (int i1 = 0; i1 < feedArray1.length(); i1++) {
JSONObject feedObj1 = (JSONObject) feedArray1.get(i1);
FeedItem item1 = new FeedItem();
item.setProfilePic(feedObj1.getString("photo_75"));
}
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance
you are looking for attachments in wrong object. "attachmetnts" is property of item.
instead of
JSONArray feedArray1 = response1.getJSONArray("attachments");
use
JSONArray feedArray1 = feedObj.getJSONArray("attachments");
in your case feedObj contains item object.
to get photo :
Remove lines :
String image = feedObj.isNull("photo") ? null : feedObj
.getString("photo");
item.setImge(image);
and change it to :
for (int i1 = 0; i1 < feedArray1.length(); i1++) {
JSONObject attachment = (JSONObject) feedArray1.get(i1);
JSONObject photo = (JSONObject) attachment.getJSONObject("photo");
item.setImge(photo);
item.setProfilePic(photo.getString("photo_75"));
item.setStatus(photo.getString("text"));
}
You can try GSON, which would directly give you a java object from your json and you would not have to parse it manually.

how to parse a JSON string which is inside a array

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

Categories

Resources