getstring() giving null value in jsonparsing - android

I am getting following response from server
{"RESPONSE":"ATTENDANCE","STATUS":"SUCCESS","projid":1,"invalid_labours":[]}.
i wrote following code of parsing
JSONObject jsonObj = new JSONObject(attendanceResponse);
String response = jsonObj.getString("RESPONSE);
String status = jsonObj.getString("STATUS);
String projectID = jsonObj.getString("projid");
JSONArray invalidLaborId = jsonObj.getJSONArray("invalid_labours");
but its giving nullpointer while fetching projid field

Replace
String projectID = jsonObj.getString("projid");
with
int projectID = jsonObj.getInt("projid");
Also it seems you are missing a double quote...
-------------------------------------------------------------------------\/
String response = jsonObj.getString("RESPONSE");

Replace
String projectID = jsonObj.getString("projid");
with
int projectID = jsonObj.getInt("projid");

projid has an integer value, try the following if you want a String :
String projectID = String.valueOf(jsonObj.getInt("projid"));

when you are try to get value from JSONObject try to use optXXX() method
in your case you are projectID is int so
int projectID = jsonObj.optInt("projid");
Difference between optXXXX() and getXXXX() method
optInt()
Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.
getInt()
Get the int value associated with a key.
This method throws: JSONException - if the key is not found or if the value cannot be converted to an integer.

Related

JSON parsing exception org.json.JSONException: No value

I am getting following JSON string that I need to parse:
response => {
"error":false,
"uid":39,
"user":{
"name":"my username",
"email":"solinpromey#gmail.com",
"created_at":"2019-05-15 13:22:19",
"updated_at":null,
"imagen":null,
"nombre":null,
"apellidos":null,
"nivel_usuario":null,
"id_usuario":39,
"unique_id":null,
"verified":null,
"cel_verificado":null,
"tel":"123456789",
"code_cel":null
}
}
I need to get the values for the fields inside key user.
I am trying as follows, but not working:
String errorMsg = jObj.getString("error_msg");
Here I am getting an exception:
W/System.err: org.json.JSONException: No value for error_msg
and consequently, the following lines are not executed:
JSONObject jObj = new JSONObject(response);
JSONObject user = jObj.getJSONObject("user");
String email = user.getString("email");
Log.d("RESPUESTA", "RESPUESTA email" + email);
That is because your JSON does not have a property named error_msg. It does have one named error, so perhaps that is what you are looking for (though it is a boolean, not a String, and it is at the top level, not inside the user object).
Use optString() it will not give you exception
Also make sure what type of field is error_msg
Like if its a String use this
String error_msg= address.optString("error_msg")
for boolean use this
boolean error_msg= address.optBoolean("error_msg")
Code snippet
JSONObject jObj = new JSONObject(response);
JSONObject user = jObj.getJSONObject("user");
String email = user.getString("email");
String error_msg= address.optString("error_msg") //string type field use optBoolean for boolean
Log.d("RESPUESTA", "RESPUESTA email" + email);
More explanation here
The difference between getString() and optString() in Json

Parse JSON using amirdew/JSON library

I'm using amirdew/JSON library, which you can find here to parse my string to JSON.
The string I retrieved is this: https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal
This is the code I have at the moment, and it is not working and I believe that it is because of the keys...
public void ParseJson (String json){
JSON json2 = new JSON(json);
String firstTag = json2.key("query").key("pages").key("extract").stringValue();
txtInfo = findViewById(R.id.txtInfo);
txtInfo.setText(firstTag);
}
The firstTag variable is null because it can't retrieve any value. I want to retrieve the text inside "extracts". How can I do it? What keys do I need?
I suggest you to use the JSONObject which is already inside the SDK. You would use it like this:
String input = "..."; // your input
JSONObject obj = new JSONObject(input);
Strings extracts = obj.getJSONObject("query").getJSONObject("pages").getJSONObject("23033").getString("extract");

How to get split string with special characters in android?

I have a string named namely "-10.00","-100.00","-1000.00". I want to get value like "10","100","1000" from that string. I have tried to get substring but did not able to get.
code i have tried
String amount = "-10.00";
String trimwalletBalance = amount.substring(0, amount.indexOf('.'));
From above i only get "-10".
String trimwalletBalance = amount.substring(1, amoun.indexOf("."));
Its very simple.
Do it like String trimwalletBalance = amount.substring(1, amount.indexOf('.'));
Instead of position 0, You should get substring from position 1
Convert it into integer and then name it positive:
String amount = "-10.00";
int amountInt = (int) Double.parseDouble(amount);
if(amountInt<0)amountInt*=-1;
Try
String amount = "-10.00";
int value = (int) Double.parseDouble(amount);
if(value < 0) value *= -1;
//value will be 10
OR
String text = amount.substring(1, amount.indexOf('.'));

Android - String to Integer then Integer to increase the String value - Json

String value comes like float value, then I need to convert it into integer after that I want increment integer value means string will automatically get new string from j-son. How to handle this problem ?
Try this :
String stringValue = "2.3";
int intValue = Integer.valueOf(stringValue);
intValue++;
stringValue = String.valueOf(intValue);
I don't my IDE with me so maybe you should have to add try/catch etc.
From String to float use
float f = Float.parseFloat("1235.00"); // replace with your string
From String to int use
int i = Integer.parseInt("741125"); // replace with your string
From int or float to String use
String s = String.valueOf(yourIntOrFloat);
For increment use
i++;
or
i=i+1;

Get first object in the JSONObject using int variable

I need to get the string in extract object. but the JSON object contains some random variable, so when I call through JSONObject pg = qr.getJSONObject(0) I get an error stating I can't use an integer.
Here is the jsonobject:
{"query":
{"pages":
{"7529378":
{"pageid":7529378,
"ns":0,
"title":"Facebook",
"extract":"<p><b>Facebook</b> is an online social networking service.</p>"
}
}
}
}
I tried the following Key structure but failed.
Iterator<?> keys = pg.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
if( pg.get(key) instanceof JSONObject ){
// get all values from JSONObject
str=pg.optString("extract");
//get ns, title, extract,.. in same way from jObjpages
}
}
Do something like:
JSONObject json = new JsonObject(your_main_string);
JSONObject query= json.getJsonObject("query");
JSONObject pages = query.getJsonObject("pages");
JSONObject id= pages .getJsonObject("7529378");
String extract = id.getString("extract");

Categories

Resources