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
Related
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();
}
{
"Query":"query",
"KMAQuery":"query",
"TotalCount":3,
"Data":[{"CollName":"kmdb_new",
"TotalCount":3,
"Count":3,
"Result":[{"title":"sampletitle",
"director":[{"directorNm":"name1","directorId":"00004544"}],
"nation":"nation1",
"company":"company1",
"genre":"genre1",
"kmdbUrl":"http://www.kmdb.or.kr/vod/vod_basic.asp?nation=K&p_dataid=01040",
"rating":[{"ratingMain":"Y","ratingDate":"19640717","ratingNo":"","ratingGrade":"","releaseDate":"","runtime":""}]]}
Here is my Json Data from OKHttp parsing.
Actually There is many same Result 2~3.
I want to parsing key name "title", "directorNm", "nation", "company", "ratingGrade" and set Model class.
How to parsing multiple Json Object and Array with Gson into Model class?
I'm finally going to use the recyclerview with model class.
If you tell me how to parsing "title" and "directorNm", I can do to rest.
For reference, I am using a AsyncTask, OKHttp, Gson etc.
If you don't understand my question or need code, please comment!
I need your help vigorously.
Here I am sharing the code settting response from Model(Pojo Class)
public void getResponse(JSONObject jsonObject){
try {
JSONObject responseJson = new JSONObject(jsonObject.toString());
JSONArray jsonArray = responseJson.getJSONArray("heroes");
for (int i = 0; i < jsonArray.length(); i++){
//getting the json object of the particular index inside the array
JSONObject jsonObject = jsonArray.getJSONObject(i);
YourPojoClass pojoObject = new YourPojoClass();
pojoObject.setName(jsonObject.getString("name"));
pojoObject.setImageurl(jsonObject.getString("imageurl"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
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");
I need to get the value of idinside studentarray. The response I get is,
{
"response": {
"student": [
{
"id": "125745",
"module": 3,
"status": 1
}
]
}
}
I tried using following code,
String userId = null;
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
userId= object.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
But it doesn't work. How do I retrieve id?
You are almost there, just you need to do this:
JSONArray students = object.getJSONArray("student");
JSONObject student = students.getJSONObject(0);
userId= student.getString("id");
Because the id value is placed in a JSONObject, then inside a JSONArray at index 0, then it is again placed inside a JSONObject.
Also don't forget to handle exceptions, the code above, is just for your understanding.
Hope that helps!!
Your value is placed in json array. So, you need to retrieve response object using getJSONObject and then get student json array via getJSONArray. Then you will be able to iterate through student objects. There is no way to magically get id from json.
Alternatively, you can map your json to Java objects using Gson, for example.
Try this :
Let all of the json is called
String serverResponse = "Response from the server";
try {
JSONObject object = new JSONObject(serverResponse);
String userId = object.getJSONObject("response").getJSONArray("student").getJSONObject(0).getString("id");
}
catch (JSONException e) {
e.printStackTrace();
}
Hope this helps.
Assuming jsonObject is a reference to your root json, you can get id of the first student:
JSONObject response = (JSONObject) jsonObject.get("response");
JSONArray students = (JSONArray) response.get("student");
int id = (int) ((JSONObject)students.get(0)).get("id");
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();
}