I'm trying to retrieve data from Json Like below :
{
comments: [
{
id: 78,
comment_user_id: 81,
comment_is_approve: 1,
comment_ads_id: 373,
comment_text: "commmmmmeeeent here ",
created_at: "2017-03-19 08:32:17",
updated_at: "2017-03-19 08:32:17",
user: {
id: 81,
first_name: "name",
last_name: "",
age: "",
email: "l#mail.com",
telephone: "234234234",
}
}
]
}
and here is my asyncTask() :
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url + 373, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Comments: ", json.toString());
try {
JSONArray comments = json.getJSONArray("comments");
// looping through All Comments
for (int i = 0; i < comments.length(); i++) {
JSONObject c = comments.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("id");
String commentText = c.getString("comment_text");
String name = "";
String phone = "";
Log.i(TAG, "doInBackground Items: " + id + " , "+ commentText);
//Loop through All user details
JSONArray arrUser = c.getJSONArray("user");
int l = 0;
JSONObject user = arrUser.getJSONObject(l++);
name = user.getString("first_name");
phone = user.getString("telephone");
// creating new HashMap
Log.i(TAG, "doInBackground Items: " + name +", " + commentText + ", " + phone);
// adding HashList to ArrayList
mapItems = new HashMap<>();
// adding each child node to HashMap key => value
mapItems.put("id", id);
mapItems.put("first_name", name);
mapItems.put("comment_text", commentText);
mapItems.put("telephone", phone);
contactList.add(mapItems);
I can get commentText and id , but i can't get any data from user array ?
should i add parantethes to users or how i can achieve that ?
Here user is not an array..it is a JsonObject
try this:
JSONObject User = c.getJSONObject("user");
String id = User.getString("id");
String first_name = User.getString("first_name");
or modify your json response to return an array instead.
Also your JSON response is invalid.
this is the valid JSON response:
{
"comments": [{
"id": 78,
"comment_user_id": 81,
"comment_is_approve": 1,
"comment_ads_id": 373,
"comment_text": "commmmmmeeeent here ",
"created_at": "2017-03-19 08:32:17",
"updated_at": "2017-03-19 08:32:17",
"user": {
"id": 81,
"first_name": "name",
"last_name": "",
"age": "",
"email": "l#mail.com",
"telephone": "234234234" //remove comma here
}
}]
}
you can check valid JSON from HERE
you have to apply nested structure like this
JSONArray arrUser1 = c.getJSONArray("user");
for (int j = 0; j < arrUser1.length(); j++) {
JSONObject c1 = arrUser1.getJSONObject(j);
name = c1.getString("first_name");
phone = c1.getString("telephone");
mapItems = new HashMap<>();
mapItems.put("id", id);
mapItems.put("first_name", name);
mapItems.put("comment_text", commentText);
mapItems.put("telephone", phone);
contactList.add(mapItems);
}
User is a JSONObject in this case. I am not sure why you have used a JSONArray.
This should be enough.
JSONObject user = c.getJSONObject("user");
name = user.getString("first_name");
phone = user.getString("telephone");
Related
I want to get current JSON object key from JSON array and pass it to another activity while Linear Layout OnClick function in android. My JSON array name extra_info has three objects inside the main_header there is string name of second object, I have to get the second object key pass to the another activity to get fields inside of that object from JSON array .
or else how to find index of current JSON object from JSON array
I have searched many codes but they are provided the all object key of an array.
JSON
"extra_info": [{
"type": "htmleditor",
"htmleditor_extra_title": "Key Features",
"ckeditor_content": ""
}, {
"type": "textfield",
"main_header": "Specifications",
"field_option": [{
"inside_single_title": "General",
"basic_opt1": [{
"option_name_extra": "Ideal for",
"option_desc_extra": "men"
}]
}, {
"inside_single_title": "Sandal Details",
"basic_opt1": [{
"option_name_extra": "Design",
"option_desc_extra": "Logo Detail"
}, {
"option_name_extra": "Closure",
"option_desc_extra": "Velcro"
}]
}]
}, {
"type": "textfield",
"main_header": "Sandal Details",
"field_option": [{
"inside_single_title": "General",
"basic_opt1": [{
"option_name_extra": "Sandal Details",
"option_desc_extra": "Sandal Details"
}]
}, {
"inside_single_title": "Sandal Details",
"basic_opt1": [{
"option_name_extra": null,
"option_desc_extra": null
}]
}, {
"inside_single_title": "Sandal Details",
"basic_opt1": [{
"option_name_extra": null,
"option_desc_extra": null
}]
}]
}],
Code:
specification = alertObj.getJSONArray(SPECIFICATION);
String spe = String.valueOf(specification);
System.out.println("*****JARRAY*****" + specification.length());
specificationdynamic = (LinearLayout) findViewById(R.id.specfication);
specifi = new TextView[specification.length()];
iconimg = new ImageView[specification.length()];
if (specification.length() > 0) {
Log.d("specificaiton", String.valueOf(specification.length()));
int jsoncount = Integer.parseInt(String.valueOf(specification.length()));
Log.d("specificaiton", String.valueOf(jsoncount));
for (y = 0; y < specification.length(); y++) {
specifiobj = specification.getJSONObject(y);
String speciobj = String.valueOf(specifiobj);
Log.d("specificaiton", String.valueOf(specifiobj));
Iterator key = specifiobj.keys();
while (key.hasNext()) {
k = key.next().toString();
System.out.println("Key : " + k + ", value : " +
specifiobj.getString(k));
}
// System.out.println(objects.toString());
System.out.println("-----------");
String types = specifiobj.getString("type");
if (types.equalsIgnoreCase("textfield")) {
hori = new LinearLayout(singleshooppingcart.this);
hori.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
hori.setOrientation(LinearLayout.HORIZONTAL);
hori.setGravity(View.TEXT_ALIGNMENT_CENTER);
hori.setPadding(5, 15, 0, 0);
specifi[y] = new TextView(singleshooppingcart.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0 f);
params.setMargins(0, 5, 0, 0);
specifi[y].setLayoutParams(params);
String main_header = specifiobj.getString("main_header");
specifi[y].setText(main_header);
specifi[y].setTextColor(Color.parseColor("#151616"));
specifi[y].setTextSize(18);
specifi[y].setTypeface(null, Typeface.BOLD);
iconimg[y] = new ImageView(singleshooppingcart.this);
LinearLayout.LayoutParams iconimgs = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
iconimgs.setMargins(0, 0, 23, 0);
iconimg[y].setLayoutParams(iconimgs);
iconimg[y].setImageResource(R.drawable.ic_keyboard_arrow_right_black_24dp);
View v = new View(getApplicationContext());
v.setLayoutParams(new LinearLayout.LayoutParams(GetPixel(1, getApplicationContext()), LinearLayout.LayoutParams.FILL_PARENT));
v.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
specifi[y].setText(main_header);
hori.addView(specifi[y]);
hori.addView(iconimg[y]);
v.setBackgroundColor(Color.parseColor("#B3B3B3"));
specificationdynamic.addView(hori);
specificationdynamic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), y, Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(getApplicationContext(), "statement wrong", Toast.LENGTH_LONG).show();
}
}
Anyone Help Thanks in advance
JSONArray arraydata = responseObj.getJSONArray("messages");
JSONObject mObject;
for(int i = 0;i<arraydata.length();i++) {
mObject = arraydata.getJSONObject(i);
String MESAGE_DATA = mObject.getString("message_data");
String USER_DATA = mObject.getString("user_data");
JSONObject JSON_MSG_DATA = new JSONObject(MESAGE_DATA);
String MSG_ID = JSON_MSG_DATA.getString("message_id");
String MSG_CUSTM_ID = JSON_MSG_DATA.getString("message_custom_id");
String MSG_TEXT = JSON_MSG_DATA.getString("message_text");
String SENDER_ID = JSON_MSG_DATA.getString("sender_id");
String RECEIVER_ID = JSON_MSG_DATA.getString("receiver_id");
String MSG_DATE_CREATED = JSON_MSG_DATA.getString("date_created");
String MSG_DATE_UPDATED = JSON_MSG_DATA.getString("date_updated");
String PARTNER_ID = JSON_MSG_DATA.getString("partner_id");
String ELAPSED_TIME = JSON_MSG_DATA.getString("elapsed_time");
JSONObject JSON_USER_DATA = new JSONObject(USER_DATA);
String USER_ID = JSON_USER_DATA.getString("user_id");
String EMAIL = JSON_USER_DATA.getString("email");
String USERNAME = JSON_USER_DATA.getString("username");
String PASSWORD = JSON_USER_DATA.getString("password");
String DEVICE_ID = JSON_USER_DATA.getString("device_id");
String DEVICE_TYPE = JSON_USER_DATA.getString("device_type");
String PROFILE_IMAGE = JSON_USER_DATA.getString("profile_image");
String PHONE = JSON_USER_DATA.getString("phone");
String GENDER = JSON_USER_DATA.getString("gender");
String BIO = JSON_USER_DATA.getString("bio");
String TITLE = JSON_USER_DATA.getString("title");
String WEB_LINK = JSON_USER_DATA.getString("web_link");
String STATUS = JSON_USER_DATA.getString("status");
String USER_DATE_CREATED = JSON_USER_DATA.getString("date_created");
String USER_DATE_UPDATED = JSON_USER_DATA.getString("date_updated");
}
You can fetchdata like this.
I have this json object as an output of a web service , I want to print each part_Name node on a separate android text view how to do that?
{
"0": [],
"1": {
"Part_ID": "1",
"Part_NAME": "part_name_one "
},
"2": {
"Part_ID": "2",
"Part_NAME": " part_name_two "
},
"3": {
"Part_ID": "3",
"Part_NAME": "part_name_three"
},
I tried this code but I don't get an output in my textview
jobj = jsonparser.makeHttpRequest("http://192.168.1.7:89/My_website/My_Webservice.php");
try {
JSONObject jsonRootObject = new JSONObject(jobj.toString());
JSONArray jsonArray = jsonRootObject.optJSONArray("Services_Parts");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("Part_NAME").toString();
data += "Node"+i+ "+ name +" +name+ " \n ";
tv2.setText(name);
}
if possible then try to change the structure of your json to something like that
[
{
"Part_ID": "1",
"Part_NAME": "part_name_one "
},
{
"Part_ID": "2",
"Part_NAME": " part_name_two "
},
{
"Part_ID": "3",
"Part_NAME": "part_name_three"
}
]
put each json object into an jsonarray .. as shown above
then parse each jsonobject and create the textview dynamically acc. to no. of jsonobject inside jsonarray
using the above ex. there are 3 jsonobject inside jsonarray
hence create 3 textview dynamically at the time of json parsing
JSONArray jsonArray = <your json array>;
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("Part_NAME").toString();
addTextView(name);
}
// add text to dynamically created textview code..
public void addTextView(String text)
{
final TextView textView = new TextView(this);
textView.setText(text);
myLinearLayout.addView(textView);
}
I am getting a Json response as below:
{
messages: [
{
id: "83",
payer_id: "5",
payee_id: "24",
payer_name: "vishal ",
payee_name: "ravi ",
payer_image: "upload/123.jpg",
payee_image: "upload/crop_110x110_1338731270_591178.jpg",
dispute_id: "43",
subject: "",
message_body: "dwedwde",
added_on: "2014-01-16 04:06:35",
sender_id: "5",
read: "1"
},
{
id: "716",
payer_id: "5",
payee_id: "6",
payer_name: "vishal ",
payee_name: "vishal ",
payer_image: "upload/123.jpg",
payee_image: "upload/yt.png",
dispute_id: "43",
subject: "",
message_body: "smthig",
added_on: "2014-05-27 02:26:04",
sender_id: "6",
read: "1"
}
],
status: "success"
}
I have coded as below for parsing.
ArrayList<HashMap<String, String>> msgList;
msgList = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(disputeURL, BackendAPIService.GET);
Log.print("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_MESSAGES)) {
System.out.println(":::::::::::::has::::::::::::");
msgArray = jsonObj.getJSONArray(Const.TAG_MESSAGES);
if (msgArray != null && msgArray.length() != 0) {
// looping through All Contacts
for (int i = 0; i < msgArray.length(); i++) {
System.out.println("::::::::::::ARRAY:::::::::::");
JSONObject c = msgArray.getJSONObject(i);
id = c.getString("id");
payee_id = c.getString("payee_id");
payer_id = c.getString("payer_id");
payer_name = c.getString("payer_name");
payee_name = c.getString("payee_name");
payer_image = c.getString("payer_image");
payee_image = c.getString("payee_image");
dispute_id = c.getString("dispute_id");
subject = c.getString("subject");
message_body = c.getString("message_body");
added_on = c.getString("added_on");
sender_id = c.getString("sender_id");
read = c.getString("read");
dispute_id = c.getString(Const.TAG_DIPUTE_ID);
System.out.println("::::::::::::sender Id::::::::::" + sender_id + ":::::::::::::::");
System.out.println("::::::::::::payee ID::::::::::" + payee_id + ":::::::::::::::");
HashMap<String, String> disputeMsgMap = new HashMap<String, String>();
disputeMsgMap.put(Const.TAG_ID, id);
disputeMsgMap.put(Const.TAG_PAYEE_ID, payee_id);
disputeMsgMap.put(Const.TAG_PAYER_ID, payer_id);
disputeMsgMap.put(Const.TAG_PAYER_NAME, payer_name);
disputeMsgMap.put(Const.TAG_PAYEE_NAME, payee_name);
disputeMsgMap.put(Const.TAG_PAYER_IMAGE, payer_image);
disputeMsgMap.put(Const.TAG_PAYEE_IMAGE, payee_image);
disputeMsgMap.put(Const.TAG_DIPUTE_ID, dispute_id);
disputeMsgMap.put(Const.TAG_SUBJECT, subject);
disputeMsgMap.put(Const.TAG_MESSAGE_BODY, message_body);
disputeMsgMap.put(Const.TAG_ADDED_ON, added_on);
disputeMsgMap.put(Const.TAG_READ, read);
disputeMsgMap.put(Const.TAG_SENDER_ID, sender_id);
msgList.add(disputeMsgMap);
}
}
So, I want to check that "sender_Id" of JSONObjects are different or not; I just want to check weather sender_id of any object is different or all are same.
You can iterate to all of your list of HashMap before you add it to the list and then check if the current sender_id is duplicated from the last list of hashmap's sender_id
example:
//TOP CODE ARE YOURS
if(msgList.size() != 0)
{
for(HashMap<String, String> hash : msgList) {
if(hash.get(sender_id) != null)
//YOU have a duplication of id
}
}
msgList.add(disputeMsgMap);
Here my valid JSON Data
{
"query": {
"pages": {
"8691": {
"pageid": 8691,
"ns": 0,
"title": "d"
}
}
}
}
this my data how to get pageid and title values.
EDIT: So I get a JSONObject pages and I want to get JSONObjects from pages, but the problem is that their name is different everytime.So I can't just do json.getJSONObject("8691");. So any suggestions how can I do that?
you can parse current json String as for getting pageid and title :
JSONObject json =new JSONObject("json string");
//get query json object
JSONObject jsonquery =json.getJSONObject("query");
//get pages json object
JSONObject jsonpages =jsonquery.getJSONObject("pages");
//get names for jsonpages
JSONArray namejsonarray = jsonpages.names();
// now get json object from jsonpages
JSONObject jsonnew =jsonpages.getJSONObject(namejsonarray.get(0));
//get pageid from jsonnew json object
String str_pageid =jsonnew.getString("pageid");
//get title from jsonnew json object
String str_title =jsonnew.getString("title");
you can try somehing like this :
JSONObject mainJson = new JSONObject("{\"query\": {\"pages\": {\"8691\": {\"pageid\": 8691,\"ns\": 0,\"title\": \"d\"}}}}");
JSONObject jsonOnb = mainJson.getJSONObject("query").getJSONObject("pages") ;
JSONObject pagesObj = jsonOnb.getJSONObject(jsonOnb.names().getString(0));
System.out.println("pageid : " + pagesObj.get("pageid"));
System.out.println("title : " + pagesObj.get("title"));
since your pageId is dynamic, you can get the name of the first index object in your JSONObject
jsonString=" {
"query": {
"pages": {
"8691": {
"pageid": 8691,
"ns": 0,
"title": "d"
}
}
}
}";
JSONObject json = new JSONObject(jsonString);
JSONObject json_query = json.getJSONObject("query");
JSONObject json_pages = json_query.getJSONObject("pages");
JSONArray pagesjsonarray = json_pages.names();
JSONObject jsonobject =json_pages.getJSONObject(pagesjsonarray.get(0));
jsonobject .get("pageid");// it will return 8691
jsonobject .get("title");// it will return d
Check this link see this
Assuming that you have already got JSONObject called pages:
final JSONObject pages = ...;
final JSONArray names = pages.names();
if (names != null && names.length() > 0) {
for (int i = 0; i < names.length(); i++) {
final String name = names.getString(i);
final JSONObject page = pages.optJSONObject(name);
if (page != null) {
final String id = page.getString("pageid");
final String ns = page.getString("ns");
final String title = page.getString("title");
System.out.println("Id " + id);
System.out.println("ns " + ns);
System.out.println("title " + title);
}
}
}
I am trying to create a JSON String in the Android application.
JSONArray jArrayFacebookData = new JSONArray();
JSONObject jObjectType = new JSONObject();
// put elements into the object as a key-value pair
jObjectType.put("type", "facebook_login");
jArrayFacebookData.put(jObjectType);
// 2nd array for user information
JSONObject jObjectData = new JSONObject();
// Create Json Object using Facebook Data
jObjectData.put("facebook_user_id", id);
jObjectData.put("first_name", first_name);
jObjectData.put("last_name", last_name);
jObjectData.put("email", email);
jObjectData.put("username", username);
jObjectData.put("birthday", birthday);
jObjectData.put("gender", gender);
jObjectData.put("location", place);
jObjectData.put("display_photo", display_photo_url);
jArrayFacebookData.put(jObjectData);
Which creates a string like this
[
{
"type":"facebook_login"
},
{
"birthday":"06\/22\/1986",
"first_name":"Harsha",
"username":"harshamv",
"location":"Bangalore, India",
"email":"hmv2206#gmail.com",
"last_name":"Mv",
"gender":"male",
"facebook_user_id":"1423671254",
"display_photo":"http:\/\/graph.facebook.com\/1423671254\/picture?type=large"
}
]
I want to create a JSON string something like this
[
"system":{
"type":"facebook_login"
},
"data":{
"birthday":"06\/22\/1986",
"first_name":"Harsha",
"username":"harshamv",
"location":"Bangalore, India",
"email":"hmv2206#gmail.com",
"last_name":"Mv",
"gender":"male",
"facebook_user_id":"1423671254",
"display_photo":"http:\/\/graph.facebook.com\/1423671254\/picture?type=large"
}
]
JSONObject jArrayFacebookData = new JSONObject();
JSONObject jObjectType = new JSONObject();
// put elements into the object as a key-value pair
jObjectType.put("type", "facebook_login");
jArrayFacebookData.put("system", jObjectType);
// 2nd array for user information
JSONObject jObjectData = new JSONObject();
// Create Json Object using Facebook Data
jObjectData.put("facebook_user_id", id);
jObjectData.put("first_name", first_name);
jObjectData.put("last_name", last_name);
jObjectData.put("email", email);
jObjectData.put("username", username);
jObjectData.put("birthday", birthday);
jObjectData.put("gender", gender);
jObjectData.put("location", place);
jObjectData.put("display_photo", display_photo_url);
jArrayFacebookData.put("data", jObjectData);
this will give you jsonObject, but not array, i don't see any point in using JSONArray. JSONObject is better in this case. you will see following output as String
{
"system":{
"type":"facebook_login"
},
"data":{
"birthday":"06\/22\/1986",
"first_name":"Harsha",
"username":"harshamv",
"location":"Bangalore, India",
"email":"hmv2206#gmail.com",
"last_name":"Mv",
"gender":"male",
"facebook_user_id":"1423671254",
"display_photo":"http:\/\/graph.facebook.com\/1423671254\/picture?type=large"
}
}
Create JSON objects for the jArrayFacebookData (not JSONArray as you have taken) and put jObjectType and jObjectData inside it.
Check this JSONObject put object method.
Update:
Your JSON is having error:
Valid JSON is:
{
"system": {
"type": "facebook_login"
},
"data": {
"birthday": "06/22/1986",
"first_name": "Harsha",
"username": "harshamv",
"location": "Bangalore, India",
"email": "hmv2206#gmail.com",
"last_name": "Mv",
"gender": "male",
"facebook_user_id": "1423671254",
"display_photo": "http://graph.facebook.com/1423671254/picture?type=large"
}
}
Final Solution:
try
{
JSONObject jArrayFacebookData = new JSONObject();
JSONObject jObjectType = new JSONObject();
jObjectType.put("type", "facebook_login");
JSONObject jObjectData = new JSONObject();
jObjectData.put("facebook_user_id", "2323");
jObjectData.put("first_name", "2323");
jObjectData.put("last_name", "2323");
//put other data here
jArrayFacebookData.put("system", jObjectType);
jArrayFacebookData.put("data",jObjectData);
System.out.println("==========> Final output => "+jArrayFacebookData.toString());
}
catch(Exception e)
{
}
how i post json string.
for(int i=0; i<iArr.size(); i++){
if(i==0){
st = "{\"userId\":" + iArr.get(i) + "}";
str += st;
}else if(i>0 && i<iArr.size()-1){
st = ",{\"userId\":" + iArr.get(i) + "}";
str+=st;
}else if(i==iArr.size()){
st = ",{\"userId\":" + iArr.get(i) + "}]}";
str+=st;
}
}
String myPost = "{\"project\":{\"Name\":"+ "\""+ title + "\""
+ ",\"Description\":" + "\""+ desc + "\""
+ ",\"createdBy\":" + usrid + ""
+ ",\"startDate\":" + "\""+ startdate + "\""
+ ",\"dueDate\":" + "\""+ duedate + "\""
+ ",\"projectLeadId\":" + leadPosition + ""
+ ",\"QAId\":" + QAssurencePosition + ""
+ ",\"TotalHour\":" +"\""+ edtHour + "\""+ "},\"members\":[";
myPost += str;
myPost +="]}";
RequestPackage myPackage = new RequestPackage();
myPackage.setUri(getaddProject);
myPackage.setMethod("POST");
myPackage.setParam("My Post",myPost+"");
new MyTask().execute(myPackage);
Toast.makeText(CreateProject.this,"Testing String: " + myPost,Toast.LENGTH_LONG ).show();
Log.d("My Post :",myPost);
}