This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I want to display all data in Key value pair in a below JSON String.
response {
community: “worker”
communitystr: "<null>";
workspace: abs;
email: "<null>";
admin: false;
persona: "<null>";
userinfo: {
info: {
contact1: {
firstname: “jon”;
lastname: “Doe”
phone: “9885678905”;
objectname: contact;
id: 9;
};
event1: {
eventname: “party”;
description: "";
order: 6;
id: 4;
objectname: events;
};
files: {
filename: “sample”;
description: "";
order: 11;
id: 11;
objectname: files;
};
};
};
As I am new to this finding difficulty. how to get the key value in array or any other accessible format ? thanks for any help
First your json format is not correct, if you try to use JSONObject or GSON library is will throw not json type exception.
Please use a correct format of json something like this.
{
[
{
username: "somename",
userId : "1"
},
{
username: "somename2",
userId: "2"
}
]
}
General JSONObject contain JSONArray or JSONObject which you can parse it using android built in JSON.
JSONArray jsonArray = new JSONArray(yourJSONArray);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject json = jsonArray.getJSONObject(i);
String username = json.getString("username"); //here is how to get username key
}
Here is how you loop through every key and value inside your JSON object
JSONArray array = new JSONObject(result);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
String value = jsonObject.getString(key)
Log.d(TAG,"key = "+key+" value = "+value); // always use tag in log cat for preventing confusion
}
Regardless anything you still need to have a proper format of JSON.
Related
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed last year.
I have a method named getPayDetails() which return type is a string
pay.getPaymentDetails() of which return type is a string and it returns the below string
[
{
"mcTtid":201657083281,
"cardLast4Digits":"0887",
"paymentType":"CREDIT CARD",
"originalPaymentCategory":{
"code":"Q",
"name":"CREDIT CARD"
}
},
{
"veTtid":21656148003,
"cardLast4Digits":"4777",
"paymentType":"GIFT CARD",
"originalPaymentCategory":{
"code":"Q",
"name":"GIFT CARD"
}
},
{
"mcTtid":201625819,
"cardLast4Digits":"8388",
"paymentType":"GIFT CARD",
"originalPaymentCategory":{
"code":"w",
"name":"GIFT CARD"
}
}
]
I need to extract the value of the attribute paymentType from the above string so the value of attribute paymentType in the above string is CREDIT CARD in a separate string variable. how can I do this?
I would recommend to use org.json library that is very easy.
After that something like this
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONArray arr = new JSONArray(jsonString);
for (int i = 0; i < arr.length(); i++)
{
String paymentType = arr.getJSONObject(i).getString("paymentType");
}
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 2 years ago.
I got stuck in parsing this JSON, I has read a some references in GitHub or google and not same for this case, can anyone give me guided or references
{
"index":
{
"data":[
{
"id":1,
"name":"John",
"room":31
}
]
}
}
EDIT: we has found a more simple json format
The solve by me
{
"data":[
{
"id":1,
"name":"John",
"room":31
}
]
}
try {
JSONObject jsonArray = new JSONObject(response);
JSONArray list = jsonArray.getJSONArray("data");
for (int i = 0; i <list.length(); i++) {
String id= list.getJSONObject(i).getString("id");
String name = list.getJSONObject(i).getString("name");
String room= list.getJSONObject(i).getString("room");
KItem KTItem = new KasusItem(id,name,room);
kItemList.add(KTItem);
}
JSONArray data = JSONObject(response).getJSONObject("index).getJSONArray("data);
for(int i=0; i<data.length; i++){
JSONObject obj = data.getJSONObject(i);
String id = obj.getString("id");
String name = obj.getString("name");
}
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 4 years ago.
Im trying to parse a json for an android app.
Its in this format:
"ticker_24h":{
"total":{
"last":24171.580293457908,
"high":30808.7,
"low":21159.009,
"vol":864.2217252755704,
"vwap":23665.865289000638,
"money":20452554.930199366,
"trades":6463
},
"exchanges":{
"NEG":{
"last":24500,
"open":23125.08,
"high":24630,
"low":22850.04,
"vol":431.26271897999953,
"vwap":24037.00642046651,
"money":10366264.745030094,
"trades":1572
},
"MBT":{
"last":23893.87002,
"open":22880,
"high":24161.57992,
"low":22700,
"vol":102.92291203000005,
"vwap":23372.09484545152,
"money":2405524.0617352244,
"trades":1835
}
} }
So far I have this but im getting a json parse error on logcat.
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONObject ticker = jsonObj.getJSONObject("ticker_24h");
JSONArray exchanges = ticker.getJSONArray("exchanges");
// looping through All exchanges
for (int i = 0; i < exchanges.length(); i++) {
JSONObject e = exchanges.getJSONObject(i);
String name = e.names().getString(i);
String price = e.getString("last");
// tmp hash map for single exchange
HashMap<String, String> exchange = new HashMap<>();
// adding each child node to HashMap key => value
exchange.put("name", name);
exchange.put("price", price);
// adding exchange to exchange list
exchangeList.add(exchange);
}
Ideally i would need a string called name with each key name and a string called price with each "last" value from these keys.
Try this code. I am using iterator to loop over the exchanges, the name of the exchange can be retrieved by iterator.next()
JSONObject exchanges = ticker.getJSONArray("exchanges");
for (Iterator i = exchanges.keys(); i.hasNext(); ) {
String keys = (String) i.next();
Util.logRanjith("Exchange name is " + keys);
JSONObject temp = (JSONObject) jsonObject.get(keys);
String last=temp.get("last").toString();
}
This question already has answers here:
How to parse JSON 2D array using Java
(2 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
Trying to parse this type of json format in java
{
"output": "success",
"result": [
{
"id": 1,
"label": "name",
},
{
"id": 2,
"label": "name_2",
}
]
}
I am getting this type of json format, now what i want to do is check first if output.equalsIgnoreCase("success)" if true then parse the second array of result.
And this is i tried so far.
try {
JSONArray myJson = new JSONArray(response);
String status = myJson.getString(Integer.parseInt("output"));
if(status.equalsIgnoreCase("success")) {
for (int i = 0; i < myJson.length(); i++) {
JSONObject obj = myJson.getJSONObject(i);
name.add(obj.getString("label"));
}
Log.e("list" , name.toString());
}
} catch (Exception e) {
}
String responceStr = ...; // here is your full responce string
try {
JSONObject responce = new JSONObject(responceStr);
String status = responce.getString("output");
if ("success".equalsIgnoreCase(status)) {
JSONArray result = responce.getJSONArray("result");
for (int i=0; i < result.length(); i++){
JSONObject jsonPair = result.getJSONObject(i);
int id = jsonPair.getInt("id");
String label = jsonPair.getString("label");
}
}
} catch (JSONException e){
}
Integer.parseInt("123") -- is OK.
Integer.parseInt("output") -- is NOT OK.
because Integer.parseInt() parses the string representation of an integer. "output" string does not represent an integer.
The response is a JSONObject, not JSONArray (it is enclosed between curly brackets). The array is the field named result.
So change myJson to JSONObject and after checking the success field,
create a new variable
JSONArray resultArray = myJson.getArray("result");
and iterate over this instead of myJson. Also you should not discard the exception since the stacktrace could provide some hint about the problems. You can add
e.printStackTrace();
in the catch block.
Alright. I have a JSON Object sent to me from a server which contains the following data:
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
}
The data I want to get is the status for the three status values. Data1, data2, and data3 always show up in that order, so I'm now trying to grab the data by index (e.g. data1 = index 0, data2 = index 1, data3 = index 2). How do I do that?
Try following:
String stat1;
String stat2;
String stat3;
JSONObject ret; //contains the original response
//Parse to get the value
try {
stat1 = ret.getJSONArray("results").getJSONObject(0).getString("status");
stat2 = ret.getJSONArray("results").getJSONObject(1).getString("status");
stat3 = ret.getJSONArray("results").getJSONObject(2).getString("status");
} catch (JSONException e1) {
e1.printStackTrace();
}
You would use JSONObject and JSONArray, the entire string is one JSONObject so you would construct one with it.
JSONObject object = new JSONObject(YOUR_STRING_OF_JSON);
Then you can access it with different get methods depending upon your expected type.
JSONArray results = object.getJSONArray("result"); // This is the node name.
String status = object.getString("status");
for (int i = 0; i < results.length(); i++) {
String resultStatus = results.getJSONObject(i).getString("status");
String type = results.getJSONObject(i).getString("type");
Log.w("JSON Result #" + i, "Status: " + resultStatus + " Type: " + type);
}
You need to surround it with a try/catch because JSON access can throw a JSONException.
Try re-factoring via a forEach loop
var testData =
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
};
var output = new Object;
var resultSet = new Object;
resultSet = testData.result;
resultSet.forEach(function(data)
{
theStatus = data['status'];
theType = data['type']
output[theType] = theStatus;
});
console.log( output['data1'] );
If you've got your models setup to mirror that data set, then you can let GSON (https://code.google.com/p/google-gson/) do a lot of your work for you.
If you want a bit more control, and want to parse the set yourself you can use JSONObject, JSONArray. There's an example of parsing and assembling a json string here: Android create a JSON array of JSON Objects