JSON request does not give anything - android

I have a bug in the code, but I can not find it. I have to read the message and the code from the JSON request below.
try {
Log.d("qwertz", json);
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("win"))
{
showDialog("Du hast etwas gewonnen", message,code);
}
else if (code.equals("false"))
{
showDialog("Du hast leider nichts gewonnen", message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
That is a JSON example
{
"server_response": {
"code": "win",
"message": "Du hast einen PzKpfw S35 739(f) gewonnen"
}
}

I advice you not to process json directly by yourself, instead you can use many libraries that will do the job for you. To mention you can use jackson or gson.
If you still want to correct your code you can try this:
JSONObject response = jsonObject.getJsonObject("server_response");
String code = response.getString("code");

Related

JSON Parsing of single array and name of Array

I need to show response on Sign Up, below is my JSON Response.
I should show password is too short(minimum is 5 characters) into one string
{ errors: { password: [ "is too short (minimum is 5 characters)" ] } }
And also I need to parse the response from the following JSON data
as Signature has already been taken
{ errors: { signature: [ "has already been taken" ] } }
Please tell me how to parse the particular data from the JSON data.
Thanks in advance!!!!
You can use below method to parse your data.
private String parseJsonData(String jsonResponse) {
try {
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONObject errorJsonObject = jsonObject.getJSONObject("errors");
JSONArray jsonArray = null;
//has method
if (errorJsonObject.has("password")) {
jsonArray = errorJsonObject.optJSONArray("password");
} else if (errorJsonObject.has(" signature")) {
jsonArray = errorJsonObject.optJSONArray("signature");
}
String errorMessage = jsonArray.getString(0);
return errorMessage;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
You can replace unwanted symbols like below code:
errorMessage.repalce("[","");
errorMessage.repalce("]","");
errorMessage.repalce("/"","");
You can use Google's Gson library to do that using the following steps:
Add dependency in your build.gradle(Module:app) file.
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
For latest version of gson library, click here
To parse JSON string to an object use the code below:
Gson gson = new Gson();
// I'm fetching my session stored JSON string
// You can fetch as per your requirement
String jsonStr = session.getJsonStr();
MyObject myObject = (MyObject) gson.fromJson(jsonStr, MyObject.class);
And if you need to convert an object to a JSON string, you can use the below code:
// I'm fetching my session stored Object here
// You can fetch as per your requirement
MyObject myObject = session.getMyObject();
String jsonStr = gson.toJson(myObject);
Make sure you design your object appropriate for the JSON string to match the data types. If you are not sure of the data types in the JSON, you can use this site or any parse and view website to view them.
Hope it helps!
Just try this,
try {
String tost = null;
JSONObject object = new JSONObject(json);
JSONObject errorObject = object.getJSONObject("errors");
if (errorObject.has("password")){
tost = "password "+errorObject.getJSONArray("password").get(0).toString();
} else if (errorObject.has("signature")){
tost = "signature "+errorObject.getJSONArray("signature").get(0).toString();
}
Toast.makeText(MainActivity.this, tost, Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
}

Getting JSON Object without Key

It is possible to retrieve a JSON object without a key name?
One more problem is that it is deep in the hierarchy. Please see this: http://jsonviewer.stack.hu/#http://gateway.marvel.com/v1/public/characters?apikey=2d0af97a020cd072d49059aa0bf13207&hash=ef7184ddbb03ed2f71da0efec112cf41&ts=1495035369
That is an intensively long JSON and has multiple objects.
I am trying to access this part of the JSON: {
"id": 1010699,
"name": "Aaron Stack", ..
I am using the following code:
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("data");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String title = post.optString("results");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I can't access it.
You can use GSON for this
compile 'com.google.code.gson:gson:2.7'
and create POJO class for the corroesponding json result using this link, Just paste your json data and create classes.
For eg your main pojo class name be JsonResponseHolder
And in your java code
try {
JsonResponseHolder jrh = new Gson().fromJson(responseString,
JsonResponseHolder.class);
List<Results> results = jrh.getData().getResults();
/// this will give the result objects
/// and be sure to convert [] arrays to list for better data handling
} catch (JSONException e) {
e.printStackTrace();
}
Hope this will help

Troubles with parsing JSON for android

I'm working on parsing some JSON in my android application, this is the code I started off with:
JSONObject jsonObject = **new JSONObject(result);**
int receivedCount = **jsonObject.getInt("CurrentCount");**
However this is causing it to error (The code that would error is surrounded with asterisks) in Android Studio, I tried using the suggestion feature which asked me if I want "Surround with try/catch" which would cause the app to crash when it launched.
This is the suggested code:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
int receivedCount = 0;
try {
receivedCount = jsonObject.getInt("CurrentCount");
} catch (JSONException e) {
e.printStackTrace();
}
This is the JSON I'm trying to pass:
[{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
Thanks in advance!
J_Dadh I think first of all you should look through the documentation on how to use Json Parser which you can find in the following Link https://www.tutorialspoint.com/android/android_json_parser.htm
EXAMPLE JSON
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
String YourJsonObject = "JsonString"
JSONObject jsonObj = new JSONObject(YourJsonObject);
JSONArray weather = jsonObj.getJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject c = weather.getJSONObject(i);
String id = c.getString("id");
String main= c.getString("main");
String description= c.getString("description");
}
as you pasted your JSON you are using [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
-If we analyze this JSON,This JSON contains a JSON ARRAY [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
having 3 JSON Objects{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}
-But when you are going to parse this JSON, you are accepting it as jsonObject = new JSONObject(result),but you should accept it asJSONArray jsonArray=new JSONArray(result);
and then you iterate a loop(e.g,for loop) on this jsonArray,accepting JSONObjects 1 by 1,then getting the values from the each JSONObject 1 by 1.
-1 more mistake in your JSON is that you are sending the strings as "5" but accepting it as getInt() that's not fair,you should send int to accept it as intas 5 (without double qoutes)
So you final JSON and code like this(as below)
JSON
[{"CurrentCount":5},{"CurrentCount":0},{"CurrentCount":1002}]
Code to Use this JSON
JSONOArray jsonArray = null;
try{
jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray[i];
receivedCount=jsonObject.getInt("CurrentCount");
}
}catch(JSONException e) {
e.printStackTrace();
}

Json String created in Wrong Format

I have to send request body in Http request in below format:
{
"flag":false,
"Ids":["xyz","abc"]
}
I was trying like:
LinkedHashMap<String, Object> requestParamsMap = new LinkedHashMap<String, Object>();
requestParamsMap.put("flag",false);
ArrayList<String> IdList = new ArrayList<>();
IdList.add("xyz");
IdList.add("abc");
requestParamsMap.put("Ids", IdList.toString());
And then I was converting requestParamsMap to json string. But I am not getting request body in desired format.
I want to create a generalized method which can return me data in this type of format, so that I can use it throughout application.
Any help would be appreciated.. !!!
Do something like this:
JSONObject object=new JSONObject();
try {
object.put("flag","xyz");
JSONArray array=new JSONArray();
array.put("xyz");
array.put("abc");
object.put("Ids",array);
//added a log to see the output
Log.e("output",object.toString());
} catch (JSONException e) {
e.printStackTrace();
}
object.toString() should contain exactly the json you want in string format. You can use a loop to populate the contents of the jsonArray or JSONObject depending on the number of items you have
Its not that though at all, output you want is JSONArray inside JSONObject and JSONObject inside another JSONObject. So, you can create them seperately and then can put in together. as below.
CODE
try {
JSONObject parent = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("lv1");
jsonArray.put("lv2");
jsonObject.put("mk1", "mv1");
jsonObject.put("mk2", jsonArray);
parent.put("root", jsonObject);
Log.d("output", parent.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
OUTPUT
{
"root": {
"mk1": "mv1",
"mk2": [
"lv1",
"lv2"
]
}
}

How to print the msg_content in textview android json here?

{
"status": "ERROR",
"msg_content": "Your old password was entered incorrectly. Please enter it again.",
"code": "400",
"msg_title": "Sorry. Error in processing your request"
}
if (str.startsWith("Bad Request"))
{
textview.setText(" ");
}
How to print inside the textview to display the msg_content using json
You need to parse json using JSON object.
JSONObject obj = new JSONObject(str);
Then find string from JSON object whatever you want.
if (obj.has("msg_content")) {
String value = obj.getString("msg_content");
textview.settext(value);
}
You will need to create a JSONObject and pass it the string as a parameter.
JSONObject obj = new JSONObject(str);
Then to find a key in the JSONObject just call, always check if the JSONObject has that key before trying to retrieve it.
if (obj.has("status"){
String status = obj.getString("status");
}
if (obj.has("msg_content"){
String content = obj.getString("msg_content");
textview.setText(content);
}
JsonReader is implemented in API 11. If you want to use it in GingerBread or below try this
Use following Code for extracting Information from JSON Objects:
try {
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if(key.equals("msg_content"))
textView.setText(jsonObject.getString(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, if u have JSON as String, u can populate an object using following code:
try {
jsonObject = new JSONObject(theJsonString);
} catch (JSONException e1) {
e1.printStackTrace();
}
I'm quite new to JSON but I would create a JsonReader and parse the JSON as per here

Categories

Resources