Parsing JSON from email header - android

I have got this kind of json data from a gmail header. How can i parse it to get the value of "delivered to" and "received" in android. Thanks in advance.
[
{"name":"Delivered-To","value":"ayuka******l#gmail.com"},
{"name":"Received","value":"by 10.140.22.233 with SMTP id 96csp129737qgn; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)"},
{"name":"X-Google-Smtp-Source","value":"ADKCNb5EL+VcU9VEZ4HxoicjzSkTx8DxijwG+0LOR+My5P4fQoiAwNEY8LYBEN/kCq+ITzM43nDg"},
{"name":"X-Received","value":"by 10.129.183.31 with SMTP id v31mr14525436ywh.24.1505250707382; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)"}
]

You just need to get the JSON objects by index and then get the json field "name" in this case
JSONArray yourData = new JSONArray(jsonFromGmail); // Put your data inside a JSONArray
String name = "";
try {
for (int i = 0; i < yourData.length(); i++) {//Loop through your JSON array
JSONObject jsonobj = null;
jsonobj = yourData.getJSONObject(i); //Get JSONObjects by index
System.out.println("name : " + i + " = " + jsonobj.getString("name"));
name = jsonobj.getString("name");
// Do whatever you want with the string
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope it helps

This works using Gson (see https://github.com/google/gson for installation instructions and documentation):
String json = "[ {\"name\":\"Delivered-To\",\"value\":\"ayuka******l#gmail.com\"}, {\"name\":\"Received\",\"value\":\"by 10.140.22.233 with SMTP id 96csp129737qgn; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)\"}, {\"name\":\"X-Google-Smtp-Source\",\"value\":\"ADKCNb5EL+VcU9VEZ4HxoicjzSkTx8DxijwG+0LOR+My5P4fQoiAwNEY8LYBEN/kCq+ITzM43nDg\"}, {\"name\":\"X-Received\",\"value\":\"by 10.129.183.31 with SMTP id v31mr14525436ywh.24.1505250707382; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)\"}]";
// parse the JSON string as an array
JsonArray array = new Gson().fromJson(json, JsonArray.class);
String deliveredTo = "";
String received = "";
// iterate through the items of the array
for (int i = 0; i < array.size(); i++) {
// parse each item as a JSON object, extract name and value from it
JsonObject element = array.get(i).getAsJsonObject();
String name = element.get("name").getAsString();
String value = element.get("value").getAsString();
// look for the relevant fields in name; if we found them, set the according values
if (name.equals("Delivered-To")) {
deliveredTo = value;
} else if (name.equals("Received")) {
received = value;
}
}
System.out.println("Delivered to: " + deliveredTo);
System.out.println("Received: " + received);
Before you use this for production, you should of course add some checks for the validity of the Json and not take assumptions like I did here (e.g.: name and value exist on every item in the array).

Works fine.
JSONArray emailHeaderObj = null;
String deliveredTo = " ";
String received = " ";
String Subject = " ";
String from = "";
try {
emailHeaderObj = new JSONArray(emailHeaderString);
for (int i = 0; i < emailHeaderObj.length(); i++) {
JSONObject element = emailHeaderObj.getJSONObject(i);
String name = element.getString("name");
String value = element.getString("value");
switch(name){
case "Date":
received = value;
break;
case "Subject":
Subject = value;
break;
case "From":
from = value;
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

parse JSON response and add it into List

I've got problem with parsing JSON. I've got response from webservice like this :
{
   "data": {
      "1": [
         {
            "id": "2",
            "name": "Szelki bezpieczeństwa",
            "quantity": "1",
            "note": null,
            "picture_id": null,
            "code": "CCCCCCCCCCCCCC"
         },
         {
            "id": "3",
            "name": "Kalosze do brodzenia, wysokie lub biodrowe",
            "quantity": "2",
            "note": "Do wymiany",
            "picture_id": null,
            "code": "DDDDDDDDDDDDDD"
         }
      ],
      "2": [
         {
            "id": "1",
            "name": "Spodnie dla pilarza z ochroną przed przecięciem, klasa min. 1 (wg PN-EN 381-5)",
            "quantity": "2",
            "note": "Uszkodzone",
            "picture_id": null,
            "code": "DAAD086F690E1C36"
         }
      ]
   }
}
I try to parse it into PART object and add it to List but somewhere I'm making mistake because object is not being parsed.
public void onResponse(String response) {
Log.e(TAG, "onResponse WHOLE: " + response);
try {
JSONObject responseJSONObject = new JSONObject(response);
String arrayString = responseJSONObject.getJSONArray("data").toString();
JSONArray responseJSONArray = new JSONArray(arrayString);
Part tempCarEquipment;
int index = 1;
for (int i = 0; i < responseJSONArray.length(); i++,index++) {
JSONObject object = responseJSONArray.getJSONObject(index);
JSONArray response2 = object.getJSONArray(Integer.toString(index));
String id = object.getJSONObject(Integer.toString(i)).getString("id");
String name= object.getJSONObject(Integer.toString(i)).getString("name");
String quantity= object.getJSONObject(Integer.toString(i)).getString("quantity");
String picture_id= object.getJSONObject(Integer.toString(i)).getString("picture_id");
String code= object.getJSONObject(Integer.toString(i)).getString("code");
tempCarEquipment = new Part(name,quantity,"",picture_id,code,id,"",0);
wholeList.add(tempCarEquipment);
Log.e(TAG, "wholeList: " + wholeList.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance fo every help! :)
JSON Parsing
You have to use the iterator for this kind of response
basic example of iterator is in this link.
You are trying to parse map as an array here:
String arrayString = responseJSONObject.getJSONArray("data").toString();
Try something like this instead:
List<JSONArray> objects = new ArrayList<>();
Iterator<String> keys = responseJSONObject.getJSONObject("data").keys();
while(keys.hasNext()) {
objects.add(responseJSONObject.getJSONObject("data").get(keys.next());
}
// rest of your stuff
Alternatively, consider using GSON to parse JSON responses using POJOs.

How to get array number JSON android

I have JSON :
{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}
My code :
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
products = json.getJSONArray("elements");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int ids = c.getInt(TAG_PID);
String id = String.valueOf(ids);
if (id.compareTo(id_kh) == 0) {
object = c.getJSONObject("links");
JSONArray courses = object.getJSONArray("courses");///???????????
//result = courses.split("[,]");
Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I dont know to get array number after "courses".
I would use HashMaps. Here you have an example (creating Hashmap from a JSON String
) how to get it from a JSON String.
Particularly for the "courses", once you have been parsed until there, I would use a HashMap<String,List<Integer>>
courses is a JSONArray, so you can do like that:
JSONArray coursesArray = linksObject.getJSONArray("courses");
UPDATE:
To get values from coursesArray :
int value = coursesArray.optInt(position);
Almost there. Once you get your
JSONArray courses = object.getJSONArray("courses");
simply iterate over its values:
// you wanted these numbers in an array
// so let's create one, with size being number of elements in
// JSONArray courses
int[] courseIds = new int[courses.length()];
for (int j=0; j<courses.length(); j++) {
// assign current number to the appropriate element in your array of ints
coursesId[j] = courses.getInt(j);
Log.d("TAG", "number: " + number);
}
The above will save these numbers in an array and print them too:
number: 15
number: 30
number: 46
number: 47
Just keep in mind that "courses" key might not exist, the array might be empty etc.

How to parse json response in android which is of the following format

I am trying to parse a json response in android for my android application. I am getting org.json.JSONException. The response is as shown below:
{
id: "12345"
email:"abc#gmail.com"
firstName:"abcd"
lastName:"efgh"
userName:"abc123"
}
I am trying to parse the response as shown below:
if (response != null) {
try {
//JSONObject jsonObj = new JSONObject(text);
// Getting JSON Array node
JSONArray contacts = new JSONArray(response.toString());
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
id = c.getString("_id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
}
} catch (JSONException e) {
e.printStackTrace();
}
Can any one let me know what mistake am I doing in parsing the response. All suggestions are welcome.
Simply replace this you are using "_id" instead of "id"
id = c.getString("id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
Change this id = c.getString("_id"); to id = c.getString("id");
in the future, you may show error in logcat when parsing like this:
catch (JSONException e) {
e.printStackTrace();
Log.e("TAG", e.getMessage());
}
There are two things I can think of , first of all you should get to know that what are [] , {} . The square brackets are arrays in json and curly demonstrate the object , so I think you are casting it wrong
1>
JSONArray contacts = new JSONArray(response.toString()); "this is culprit"
You should change it to
JSONObject. Use JSONObject in place of JSONArray
and Secondly
2> change this key id = c.getString("_id");to
id = c.getString("id");
Make sure You are getting and writing spellings of all keys right else it would generate exception.

Failed to Parse JSON Response

I have JSON Response like this.I have tried a lot but unable to parse the Values.
This one is my Actual Response...
{"ResponseCode":"000","ResponseDescription":"Successful","SystemServiceID":["0000"],"SystemServiceName":["Test"],"ProductID":["000"],"ProductName":["Test"],"ProductDescription":["Test product"],"MinimumValue":[10000],"MaximumValue":[500000],"ImageURL":[null],"Country":["AAAA"],"CompanyID":["1"],"CompanyName":["Test"],"FieldLevel":["2"],"FieldInfo":["{\"Field1\":{\"Field Name\":\"Phone Number\",\"Field Type\":\"Number\",\"Validation\":{\"Min\":\"4\",\"Max\":\"8\"}},\"Field2\":{\"Field Name\":\"Email\",\"Field Type\":\"String\",\"Validation\":{\"Regular Expression\":\"abcd\",\"Min Length\":\"10\",\"Max Length\":\"20\"}}}"]}
Out of this i am able to parse all the field expect the below one...
{
"Field1":
{
"Field Name":"Phone Number",
"Field Type":"Number",
"Validation":{"Min":"4","Max":"8"}
},
"Field2":
{
"Field Name":"Email",
"Field Type":"String",
"Validation":{"Regular Expression":"abcd","Min Length":"10","Max Length":"20"}
}
}
I also want to fetch the value of Validation":{"Min":"4","Max":"8"} this field.Like it has max value 4 and min value is 8.
Any Help will be appreciated.
Thanks in Advance ... :)
Here is the code to read Min And Max values
JSONObject parentObject = new JSONObject(Json_String);
JSONObject field1 = parentObject.getJSONObject("Field1");
JSONObject validation = field1.getJSONObject("Validation");
String min = validation.getString("Min");
String max = validation.getString("Max");
Assuming your JSON string is well formed.
Since in your response you are not getting the "\" into JSON so you need to some modifications into that like (update : It seems that replacement not required here)
String json = "{\"Field1\":{\"Field Name\":\"Phone Number\",\"Field Type\":\"Number\",\"Validation\":{\"Min\":\"4\",\"Max\":\"8\"}},\"Field2\":{\"Field Name\":\"Email\",\"Field Type\":\"String\",\"Validation\":{\"Regular Expression\":\"abcd\",\"Min Length\":\"10\",\"Max Length\":\"20\"}}}";
// json.replace("\\", ""); // I verified that parsing works well without replacement too
try {
JSONObject parentObject = new JSONObject(json);
JSONObject field1 = parentObject.getJSONObject("Field1");
JSONObject validation = field1.getJSONObject("Validation");
String min = validation.getString("Min");
String max = validation.getString("Max");
System.out.println("Min ::::::: " + min);
System.out.println("MAx ::::::: " + max);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

data from a jsonobject in android

The below is called from a string url and returns a json object which has an json array inside, but something else is not working, can anyone show me how to access the data inside?
{"data":[{"8196":{"booking_id":"8150","client_id":"107","venue_id":null}}]
String jsonStr = "{\"data\":[{\"8196\":{\"booking_id\": \"8150\",\"client_id\": \"107\",\"venue_id\": null}}]}";
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Iterator it = o.keys();
while (it.hasNext()) {
String name = (String) it.next();
o = o.getJSONObject(name);
int bookingId = o.getInt("booking_id");
int clientId = o.getInt("client_id");
int venueId = o.optInt("venue_id");
Log.v("TEST", String.format("Booking ID: %s -- Client ID: %s -- Venue ID: %s", bookingId, clientId, venueId));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess this is what you'll want. By the way, the JSON you posted is malformed. It's missing a } in the end.
You first need to decode the JSON string. The JSON sting you got in return is actually a serialized version of a JSON object.
You need to decode that string into a native Java Object.
There are a number of methods to this in Java. You can start by checking out the Java section at json.org.
I think the problem is that the value of key venue_id is null. You can replace null value with empty string(""), try it.

Categories

Resources