How to get value from JSON in Android - java

I have JSON response:
{"error":100,"result":"{\"distance\":2.4,\"duration\":5,\"price\":0}"}
From this response I want to get a "distance" value for example. How to do it?
I tried to do like this:
String distance = String.valueOf(finalResponseDataJOSNObject.getDouble("distance"));
but string value is null. Any ideas?
UPDATE:
Finally we discovered that it was back-end issue and we fixed it. No additional operations like JSONObject conversation to String, special character removal, etc. was necessary.
Simply:
String distance =
String.valueOf(finalResponseDataJOSNObject.getJSONObject("result").getDouble("di‌​stance"));

Try this...
String json = "{\"error\":100,\"result\":{\"distance\":2.4,\"duration\":5,\"price\":0}}";
try {
JSONObject jsonObject = new JSONObject(json);
double distance = jsonObject.getJSONObject("result").getDouble(
"distance");
Log.i("DISTANCE", String.valueOf(distance));
} catch (JSONException e) {
e.printStackTrace();
}

The distance is in a JSONObject under result only. So you have to getJSONObject("result").getDouble("distance").

You can do this in following way:
Remove special character from json string and convert back to json object and process it accordingly:
String json = "{\"error\":100,\"result\":{\"distance\":2.4,\"duration\":5,\"price\":0}}";
try{
JSONObject jsonObject = new JSONObject(json.replaceAll("\"", ""));
JSONObject jsonObject2=jsonObject.getJSONObject("result");
String distance=jsonObject2.getString("distance");
double convertedDistance=Double.valueOf(distance);
Log.i("DistanceInformation", "My Distance from json is="+distance);
}catch(JSONException e)
{
e.printStackTrace();
}

Thanks for you all who responded.
Finally we discovered that it was back-end issue and we fixed it. No additional operations like JSONObject conversation to String, special character removal, etc. was necessary.
Simply:
String distance =
String.valueOf(finalResponseDataJOSNObject.getJSONObject("result").getDouble("di‌​stance"));

Related

How to convert string into JSONObject?

I have a string with value abc#xyz.com.
I have to pass this value to server like:
{"email":"abc#xyz.com"}
I am passing value to server like this using okhttp:
Map<String, String> map = new HashMap<>();
map.put("email", email);
new PostMethodWithProgress(login_url, map, this, new Callback()
{
#Override
public void done(String reply)
{
try
{
JSONObject object = new JSONObject(reply);
if (object.getString("status").equals("200"))
{
//Toast Success Message
}
else
{
//Toast Failure Message
}
}
catch (Exception e)
{
Log.e("ASA", "Error is: " + e);
}
}
}).execute();
How do i do it?
You can simply use JSONObject to achieve this
JSONObject jsonObject = new JSONObject();
jsonObject.put("email", "abc#xyz.com");
String result = jsonObject.toString();
Output:
{"email":"abc#xyz.com"}
Use Google Gson convert string to model and model to string easily
ConvertModel convertModel = new Gson().fromJson(reply, ConvertModel .class);
Then you can validate easily
easy way use this code to pass jsonobject as string in okhttp
String jsonString = "";
try {
JSONObject obj = new JSONObject();
obj.put("email", "abc#xyz.com");
obj.put("pwd", "12356");
jsonString = obj.toString();
//out put like this -> {"email":"abc#xyz.com","pwd":"123456"}
Log.d("JsonString__",jsonString);
}catch (Exception e){};
JsonObject is a modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObject, JSONArray, Strings, Booleans, Integers, Longs, Doubles or NULL.
for your case key is email and value is abc#xyz.com so as I told JsonObject we can put both key and value pair like below -
JsonObject object = new JsonObject();
object.put("email","abc#xyz.com");
If we convert above JsonObject to string then its value would be -
{"email":"abc#xyz.com"}
hope this will help you.
try out this code with your data.
/**
* This method is used to create text size and color code json and store it in json object.
*
* #param textSize text size entered into edit text.
* #param colorOfPreview text color of custom text color.
* #return return json object of created text size and color.
*/
private String createJSONObject(String textSize, int colorOfPreview) {
JSONObject jsonObject = new JSONObject();
try {
// put your values here
jsonObject.put("textSize", textSize);
jsonObject.put("textColor", colorOfPreview);
return jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject.toString();
}

Iterate all json object and replace values

I have following JSON:
{
"data":{
"attributes":{
"external-event-url":"http://example.com",
"is-sponsors-enabled":"true",
"is-ticketing-enabled":"true",
"timezone":"UTC",
"name":"${name_variable}",
"ends-at":"2020-01-02T23:59:59.123456+00:00",
"starts-at":"2020-01-01T23:59:59.123456+00:00"
},
"type":"event"
}
}
I have to iterate through json objects and replace the value of variable starts with ${ e.g. ${name_variable}
and new json should be in same format(with replace value of variable mentioned ${})
How do i iterate such complex Json object and replace the values in variables
I've tried below code but not working as expected:
public Map<String, String> mapfillData(String jsonstr) {
Map<String, String> map = new HashMap<String, String>();
try {
JSONObject jsonObject = new JSONObject(jsonstr);
String[] keys = JSONObject.getNames(jsonObject);
for (String key : keys) {
try {
if (jsonObject.get(key).toString().startsWith("${")) {
map.put(key, System.getProperty(jsonObject.get(key).toString()
.replace("${", "").replace("}", "")));
} else {
if(isJSONValid(jsonObject.get(key).toString())){
mapfillData(jsonObject.get(key).toString());
}else{
map.put(key, jsonObject.get(key).toString());
}
}
} catch (Exception e) {
}
}
} catch (JSONException e) {
System.err.printf(jsonstr + " is not valid Json", e);
}
return map;
}
To check whether its a valid JSON Object
public boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
// edited, to include #Arthur's comment
// e.g. in case JSONArray is valid as well...
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
Your problem is that while you are trying to recursively process the JSON, at each level of recursion, you're processing a different JSON document and writing data into a different Map.
Your function takes a string and then parses it into a JSONObject. You create a Map to hold some data. The first time through mapfillData, you're only going to find one key, data. Then, assuming that your if logic works correctly (I didn't try to run it), you're going to render the contents of data into another string and recursively call mapfillData.
Now you're in the second call to mapfillData, and you create another Map. This time through you find attributes and call mapfillData a third time. In this third invocation, you find some variables and replace them when writing the values to Map. At the end of the function, you return the Map, but the caller (the second invocation of mapfillData) doesn't do anything with the returned Map, and all your data is lost.
I would:
Parse the JSON once, then recurse through the JSONObject structure. In other words, the recursive function should take JSONObject.
Just replace the JSON elements in-place.
Or, if you want to flatten the elements and collect them into a Map, then instantiate the Map up-front and pass it into the recursive function.
To convert more easily, you can use the Jackson lib to do the hard stuff:
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{
"data":{
"attributes":{
"external-event-url":"http://example.com",
"is-sponsors-enabled":"true",
"is-ticketing-enabled":"true",
"timezone":"UTC",
"name":"${name_variable}",
"ends-at":"2020-01-02T23:59:59.123456+00:00",
"starts-at":"2020-01-01T23:59:59.123456+00:00"
},
"type":"event"
}
}";
// considering JSONObject matches the Json object structure
JSONObject jsonObject = mapper.readValue(jsonString , JSONObject.class);
Then a little bit of reflection to handle any JSON object fields dynamically:
// with parsed JSON to Object in hands
Class<?> clazz = jsonObject.getClass();
for(Field field : clazz.getDeclaredFields()) {
if(!field.getType().getName().equals("String"))
break;
field.setAccessible(true);
String fieldValue = field.getValue().toString();
if(fieldValue.startsWith("${"))
field.set(jsonObject, fieldValue.replace("${", "").replace("}", ""));
else
// desired treatment
}

How to fix 'JsonNull cannot be cast to JsonObject'

I call a post API which responds with details on specific addresses, however some of the responses that get returned have no data so they'll be returned as null. How do I stop the casting error in my code?
I currently only get the data as a Json Object and I'm not sure how to rework my code that so when a JsonNull Element gets returned I can handle that data.
JsonElement element = new JsonParser().parse(jsonString);
JsonObject jsonObject = element.getAsJsonObject();
jsonObject = jsonObject.getAsJsonObject("response"); // This is either an object or it is null
String buildName = jsonObject.get("buildingName").getAsString();
String buildNum = jsonObject.get("premisesNumber").getAsString();
String streetName = jsonObject.get("streetName").getAsString();
What I expect to be returned would be either the address details for valid addresses or no information at all for the invalid addresses.
The error that gets produced is this:
java.lang.ClassCastException: com.google.gson.JsonNull cannot be cast to com.google.gson.JsonObject
Before getAsString() check for isJsonNull(). It'll return true if object is Null.
You can rewrite your code as below
String buildName= (jsonObject.get("buildingName").isJsonNull ? null : jsonObject.get("buildingName").getAsString());
Normally is a good idea validate the data is JSON valid
public static boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
Function above will return you true in case the string is a valid JSON object(could be an object or an array of objects).
After that you can continue parsing using Jackson lib or the GSON lib

How to check if a key exists in Json Object and get its value [duplicate]

This question already has answers here:
How to check if a JSON key exists?
(13 answers)
Closed 5 years ago.
Let say this is my JSON Object
{
"LabelData": {
"slogan": "AWAKEN YOUR SENSES",
"jobsearch": "JOB SEARCH",
"contact": "CONTACT",
"video": "ENCHANTING BEACHSCAPES",
"createprofile": "CREATE PROFILE"
}
}
I need to know that either 'video` exists or not in this Object, and if it exists i need to get the value of this key. I have tried following, but i am unable to get value of this key.
containerObject= new JSONObject(container);
if(containerObject.hasKey("video")){
//get Value of video
}
Use below code to find key is exist or not in JsonObject. has("key") method is used to find keys in JsonObject.
containerObject = new JSONObject(container);
//has method
if (containerObject.has("video")) {
//get Value of video
String video = containerObject.optString("video");
}
If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject.
Use:
if (containerObject.has("video")) {
//get value of video
}
From the structure of your source Object, I would try:
containerObject= new JSONObject(container);
if(containerObject.has("LabelData")){
JSONObject innerObject = containerObject.getJSONObject("LabelData");
if(innerObject.has("video")){
//Do with video
}
}
Please try this one..
JSONObject jsonObject= null;
try {
jsonObject = new JSONObject("result........");
String labelDataString=jsonObject.getString("LabelData");
JSONObject labelDataJson= null;
labelDataJson= new JSONObject(labelDataString);
if(labelDataJson.has("video")&&labelDataJson.getString("video")!=null){
String video=labelDataJson.getString("video");
}
} catch (JSONException e) {
e.printStackTrace();
}
containerObject = new JSONObject(container);
if (containerObject.has("video")) {
//get Value of video
}
Try
private boolean hasKey(JSONObject jsonObject, String key) {
return jsonObject != null && jsonObject.has(key);
}
try {
JSONObject jsonObject = new JSONObject(yourJson);
if (hasKey(jsonObject, "labelData")) {
JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
if (hasKey(labelDataJson, "video")) {
String video = labelDataJson.getString("video");
}
}
} catch (JSONException e) {
}
JSONObject class has a method named "has".
Returns true if this object has a mapping for name. The mapping may be NULL.
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
JSONObject root= new JSONObject();
JSONObject container= root.getJSONObject("LabelData");
try{
//if key will not be available put it in the try catch block your program
will work without error
String Video=container.getString("video");
}
catch(JsonException e){
if key will not be there then this block will execute
}
if(video!=null || !video.isEmpty){
//get Value of video
}else{
//other vise leave it
}
i think this might help you

How to parse multidimensional json array in java

I have a two dimensional JSON array object like below
{"enrollment_response":{"condition":"Good","extra":"Nothig","userid":"526398"}}
I would like to parse the above Json array object to get the condition, extra, userid.So i have used below code
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("D:\\document(2).json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("enrollment_response");
System.out.println("Condition:" + name);
String name1 = (String) jsonObject.get("extra");
System.out.println("extra: " + name1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
Its throwing an error as
"Exception in thread "main" java.lang.ClassCastException:
org.json.simple.JSONObject cannot be cast to java.lang.String at
com.jsonparser.apps.JsonParsing1.main(JsonParsing1.java:22)"
Please anyone help on this issue.
First of all: Do not use the JSON parsing library you're using. It's horrible. No, really, horrible. It's an old, crufty thing that lightly wraps a Java rawtype Hashmap. It can't even handle a JSON array as the root structure.
Use Jackson, Gson, or even the old json.org library.
That said, to fix your current code:
JSONObject enrollmentResponseObject =
(JSONObject) jsonObject.get("enrollment_response");
This gets the inner object. Now you can extract the inner fields:
String condition = (String) enrollmentResponseObject.get("condition");
And so forth. The whole library simply extends a Hashmap (without using generics) and makes you figure out and cast to the appropriate types.
Below line,
String name = (String) jsonObject.get("enrollment_response");
should be
String name = jsonObject.getJSONObject("enrollment_response").getString("condition");
Value of enrollment_response is again a Json.
This works, but trust me: change library.
JSONObject jsonObject = (JSONObject) obj;
JSONObject name = (JSONObject) jsonObject.get("enrollment_response");
System.out.println("Condition:" + name);
String name1 = (String) name.get("extra");
System.out.println("extra: " + name1);

Categories

Resources