I made a chat app using socket.io and node.js and I got data like as in JSON object.
Here is my code
db.query('select email from users ', function(err, rows , field) {
if (err) throw err;
let getuser={"get":rows};
socket.emit('getuser',getuser);
});
In android I get the data and show the email data using Toast.makeText
JSONObject data = (JSONObject) args[0];
try {
String get =data.getString("get");
Toast.makeText(getApplicationContext(), get, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {}
But I wanna show email list (userlist) by using a simple ListView.
How can I get a string array from a JSON object?
Please help me.
You need to get JSON Array from JSONObject then convert it to List of model class by loop and parse it or by GSON Library then show result list on ListView
JSONObject data = (JSONObject) args[0];
try {
JSONArray userlist = data.getJSONArray("get");
} catch (JSONException e) {}
Related
How to parse more then one JSON which each ending with null character(through socket TCP/IP).
{"ObjectID":"UHJvY1dpcmVsZXNzTXNn","DeviceCode":"RUNEOjI=","ActiveInputNames":"Q2hlY2sgaW4gRmFpbA==","DeviceInputNo":"999999","Activation":false,"Reset":true,"LocationID":"","LocationGroupText":"","ProtocolText":"","CallBackNo":"OTE5MTgyNTcyMjQ5"}��{"ObjectID":"VFBpbmdPYmplY3Q="}��
As you can see the above response which has 2 JSON's each ending with null character...I can easily parse the single JSON but unable to parse more then one JSON..
It would be great if any one suggest any solutions!!
You can split the json string using the �� and loop through the array:
String s = "{\"ObjectID\":\"UHJvY1dpcmVsZXNzTXNn\",\"DeviceCode\":\"RUNEOjI=\",\"ActiveInputNames\":\"Q2hlY2sgaW4gRmFpbA==\",\"DeviceInputNo\":\"999999\",\"Activation\":false,\"Reset\":true,\"LocationID\":\"\",\"LocationGroupText\":\"\",\"ProtocolText\":\"\",\"CallBackNo\":\"OTE5MTgyNTcyMjQ5\"}��{\"ObjectID\":\"VFBpbmdPYmplY3Q=\"}��";
String[] array = s.split("��");
for (String string: array){
try {
JSONObject json = new JSONObject(string);
//do what ever you want with this
} catch (JSONException e) {
Log.e("Error",Log.getStackTraceString(e));
}
}
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();
}
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");
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
{
"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