Can't parse json object(android) - android

Sorry for my English, I can't parse json object like this:
{
"user": {
"id": 34,
"last_login": {
"date": "2015-07-30 11:22:34.000000",
"timezone_type": 3,
"timezone": "Europe/Oslo"
}
}
}
I don't know, why it's not working. I need parse last_login, but I can't do this
My code
JSONObject jsonTable = json.getJSONObject("user");
if(jsonTable.length() > 0) {
check = true;
ProfileDetalisObject pfDet = new ProfileDetalisObject();
pfDet.setId(jsonTable.getString(TAG_ID));
JSONObject date = jsonTable.getJSONObject("last_login");
if(date.length() > 0) {
Iterator<String> iteratorDate = date.keys();
while( iteratorDate.hasNext() ) {
String currentKeySensor = iteratorDate.next();
JSONObject objDate = date.optJSONObject(currentKeySensor);
if(objDate != null) {
pfDet.setDate(objDate.getString("date"));
pfDet.setTimezone_type(objDate.getString("timezone_type"));
pfDet.setTimezone(objDate.getString("timezone"));
}
}
}
I can't parse last_login.

last_login is normal json object (aka dictionary), so you do not need any iterators, just reach the keys directly:
JSONObject date = jsonTable.getJSONObject("last_login");
pfDet.setDate(date.getString("date"));
pfDet.setTimezone_type(date.getString("timezone_type"));
pfDet.setTimezone(date.getString("timezone"));

Related

Remove The Json Value From Json

I want to remove json value from below json file .
This is my json object :
{
"Approximation": {
"name": "Approximation",
"description": [
"Approximation",
"Approximation",
"Approximation"
],
"video": [
"evideo/package1/maths/Approximation/349188_f2ba28819a74355a456ef91d95451b71/349188_f2ba28819a74355a456ef91d95451b71/349188.mpd",
"evideo/package3/maths/approxomation/396183_Approximation/396183_fcedf516e0f5c935d561d486058fa6e0/396183.mpd",
"evideo/package2/maths/approxomation/387010_01approximation/387010_949440b1082fea19faa7dcb4aebf0b43/387010.mpd"
]
}
}
and this is what I'm trying
Code :
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
jsonArr.remove(i);
children = new ArrayList<ChildrenEvent>();
et = new Events(jsonObj.optString("name"));
ct = new ChildrenEvent(jsonObj.optString("description"));
langs.add(et);
children.add(ct);
}
I am not sure what you are trying to achieve here. You don't need to remove the key "Approximation" to get the data.
This is how you parse this JSON.
{
"Approximation": {
"name": "Approximation",
"description": ["Approximation", "Approximation", "Approximation"],
"video": ["evideo/package1/maths/Approximation/349188_f2ba28819a74355a456ef91d95451b71/349188_f2ba28819a74355a456ef91d95451b71/349188.mpd", "evideo/package3/maths/approxomation/396183_Approximation/396183_fcedf516e0f5c935d561d486058fa6e0/396183.mpd", "evideo/package2/maths/approxomation/387010_01approximation/387010_949440b1082fea19faa7dcb4aebf0b43/387010.mpd"]
}
}
Code,
JSONObject mainObj = new JSONObject(json_string);
JSONObject appproxObj = mainObj.getJSONObject("Approximation");
// Parse name
String name = appproxObj.getString("name");
et = new Events(name);
langs.add(et);
// Parse descriptions
JSONArray descriptions = appproxObj.getJSONArray("description");
children = new ArrayList<ChildrenEvent>();
for (int i = 0; i < descriptions.length(); i++ ) {
String description = descriptions.getString(i);
ct = new ChildrenEvent(description);
children.add(ct);
}
Still if you need the JSON without key "Approximation", the variable appproxObj has the JSON without the key.
There is a method in JsonObject, that is remove(). It will help you to remove any key from jsonObject;
Use this:-
jsonObject.remove("key");

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 catch JSON null result on Android?

I have an Android Application that invoke a REST webservice and get the JSON answer.
When I enter a wrong parameter I can catch the error without problem but sometimes some results on the JSON are null. How can I catch that situation?
My Android code:
try {
JSONObject jsonObj = new JSONObject(results);
JSONArray result = jsonObj.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String string04 = c.getString("string04");
String string05 = c.getString("string05");
TextView txt1 = (TextView)findViewById(R.id.textView1);
txt1.setText(string04);
TextView txt2 = (TextView)findViewById(R.id.textView2);
txt2.setText(string05);
JSONArray dest = c.getJSONArray("dest");
for (int o = 0; o < dest.length(); o++) {
JSONObject d = dest.getJSONObject(o);
JSONArray pred = d.getJSONArray("pred");
for (int u = 0; u < pred.length(); u++) {
JSONObject e = pred.getJSONObject(u);
String string13 = e.getString("string13");
TextView txt4 = (TextView)findViewById(R.id.textView4);
txt4.setText(string13);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("error", e.getMessage());
}
A good JSON result would be like this:
{
"result": [{
"string01": "104",
"string02": "104 - blablabla",
"string03": "104",
"string04": "blobloblo",
"string05": "blablabla",
"dest": [{
"pred": [{
"time": 1461348846,
"sec": 102,
"min": 1,
"string11": "514-String",
"string12": "Some String",
"string13": "Some other String",
"number": 0
}]
}]
}]
}
But sometimes, when there is no data to show, I get something like this:
{
"result": [{
"string01": "104",
"string02": "104 - blablabla",
"string03": "104",
"string04": "blobloblo",
"string05": "blablabla",
"dest": [{"pred":[]}]
}]
}
The JSON parser has "opt" methods which will return NULL if there's no object for the matching condition. These methods are there similar to get methods.
E.g: getJSONObject("column") will throw an exception if there isn't a value for "column"
optJSONObject("column") will simply return a NULL value if it doesn't exist. I personally find the "opt" methods handy when working with JSONs whose values might be missing at runtime.

android json parsing error - JSONArray cannot be converted JSONObject

i am converting a xml content into JSON content and the content is as follows
{
"response":
{
"seatlist":
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
},
"userid":"8970ca285d9c4e4d",
"seatnum":12,
"session":"online"
}
}
I am able to get the userid and seatnum in the following way
JSONObject response = json.getJSONObject("response");
out.setUserid(response.getString("userid"));
out.setBalance(Double.valueOf(response.getString("balance")));
Now the problem is i need to parse the following content and need to get "num" value
"seatlist":
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
}
here is my code i am using
JSONObject objList = response.getJSONObject("seatlist");
String n = String.valueOf(objList.getJSONObject("seat"));
if(objList.getJSONObject("seat").get("userId").equals(userId))
{
String num = String.valueOf(objList.getJSONObject("seat").get("num"));
out.setSeatNum(Integer.valueOf(num));
}
if i have one seat value i am able to get "num" value else i am getting JSON exception
Pls give me a suggestion in this.....
You want to get a JSONArray in an JSONObject. That is not possible.
Get the Array and then iterate through the array to get the objects:
JSONObject objList = response.getJSONArray("seatlist");
for(int i = 0, i<objList.lenght(); i++){
JSONObject json = objList.get(i);
}
{
"response":
{
"seatlist":
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
},
"userid":"8970ca285d9c4e4d",
"seatnum":12,
"session":"online"
}
}
means an object with an object called response. this contains an object called seatlist. this contains 2 objects called seat (but this is wrong! this should be an array!). and so on..
to read this you can use
JSONObject json = new JSONObject(yourresponse);
JSONObject response = json.getJSONObject("response");
JSONObject seatlist = response.getJSONObject("seatlist");
JSONObject userid = response.getJSONObject("userid");
JSONObject seatnum = response.getJSONObject("seatnum");
JSONObject session = response.getJSONObject("session");
now seatlist contains.
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
}
which is wrong, since it contains 2 elements with same name. Now you can either call it by index like this:
JSONObject seat1 = seatlist.getJSONObject(1);
JSONObject seat2 = seatlist.getJSONObject(2);
seat1.getString("balanace"); seat1.getInt("num");
or you can iterate through the JSONObject.
At least it should be an Array instead of JSONOBject.
This means it should look like this.
{
"response": {
"seatlist": [
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
],
"userid":"8970ca285d9c4e4d",
"seatnum":12,
"session":"online"
}
}

is my JSON response correct? and why i see this exception when i try to retrieve it?

my problem is that i have an asp. web service .. and it gives me the following result when i invoke it :
[
{
"_OrderDetails": [
{
"ProductName": "FUCHS SUPER GT SAE 10W30 6X5 / FP10100010102",
"TotalAfterDiscount_Lc": "7500",
"MeasureUnitName": "كرتونة",
"TotalPrice_Lc": "7500",
"PricePerUnit_Lc": "75",
"Quantity": "100"
}
],
"Id": "274",
"OrderDate": "4/10/2014 12:00:00 AM",
"Number": "16",
"CustomerName": "الأسد",
"Note": ""
}
]
and in the main activity i do the following :
Gson gson = new Gson();
Log.e("Response", responseJSON);
if (responseJSON != null) {
try {
JSONObject jsonObj = new JSONObject(responseJSON);
//JSONArray jsonarr =new JSONArray();
// details=jsonObj.getJSONObject(0);
// Getting JSON Array node
details = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String product = c.getString(TAG_PRODUCT);
Log.e("prodeuct",product+"");
}
i see the response in the logcat correctly but when i try to get any object from the array i see a JSON exception it says :
JSON array can't be converted to JSON object !!!
please can anyone help me??
Because your json return jsonarray and you are try to access jsonobject.
Change your code:
if (responseJSON != null) {
try {
JSONArray jsonObj = new JSONArray(responseJSON);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
// your code
}
Chang to JSONArray
if (responseJSON != null) {
try {
JSONArray array = new JSONArray(responseJSON)
}
http://jsonviewer.stack.hu/ use it to view your json and resolve it accordingly. you are using json array as json object.
use these:
JSONObject jsonObj = new JSONObject(responseJSON);
to
JSONArray jr = new JSONArray(responseJSON);

Categories

Resources