This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
Hi i want to traverse this json data using android fast networking library but i am not able to do so. Can someone please suggest a way to be able to fetch id and filename of all the objects in the array?
Note -It has to be done using ANDROID FAST NETWORKING LIBRARY -https://github.com/amitshekhariitbhu/Fast-Android-Networking
[
{
"_id": "598ae8773376673353ef6da6",
"filename": "nldcjjzpesyhkkx1502275703450.jpg",
"votes": 33,
"__v": 0
},
{
"_id": "598ae83b3376673353ef6da5",
"filename": "xlwkfcxicwhqibw1502275643486.jpg",
"votes": 31,
"__v": 0
},
{
"_id": "598a2e7000c6717c3c04e534",
"filename": "ndkiqptbifqmnjz1502228078447.jpg",
"votes": 19,
"__v": 0
},
{
"_id": "5989ece9673738c027377710",
"filename": "seicmgkzubzavfy1502211303478.jpg",
"votes": 13,
"__v": 0
}
]
You can use GSON lib or you can retrieve using for loop like this:
try {
JSONArray jsonArray = new JSONArray(yourResponseStrOrJson);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("ID", jsonObject.getString("_id"));
//TOTO retrive other element
}
}catch (JSONException e){
e.printStackTrace();
}
Related
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 3 years ago.
How to parse this json response using Java
{
"Name": {
"name_description": "NIL",
"date": "NIL"
},
"Age": {},
"City": {},
"SOAP": [
["content", "subtopic", "topic", "code"],
["I advised her to call 911, which he did.", "history of present illness", "subjective", "{}"]
]
}
You'd have to use an external library like json-simple
Read more about it here
Use a library called org.json, it is honestly the best java json library.
for example:
import org.json.JSONObject;
private static void createJSON(boolean prettyPrint) {
JSONObject tomJsonObj = new JSONObject();
tomJsonObj.put("name", "Tom");
tomJsonObj.put("birthday", "1940-02-10");
tomJsonObj.put("age", 76);
tomJsonObj.put("married", false);
// Cannot set null directly
tomJsonObj.put("car", JSONObject.NULL);
tomJsonObj.put("favorite_foods", new String[] { "cookie", "fish", "chips" });
// {"id": 100001, "nationality", "American"}
JSONObject passportJsonObj = new JSONObject();
passportJsonObj.put("id", 100001);
passportJsonObj.put("nationality", "American");
// Value of a key is a JSONObject
tomJsonObj.put("passport", passportJsonObj);
if (prettyPrint) {
// With four indent spaces
System.out.println(tomJsonObj.toString(4));
} else {
System.out.println(tomJsonObj.toString());
}
}
I've got a method below, which is parsing JSON. However I've run into an error (which you can see from the title), where it is saying "org.json.JSON.typeMismatch" .
Trying to log the names that are getting output however having no luck. I've little experience with cracking JSON (as you can probably tell from this), so wondering how to go about fixing this issue.
private Boolean parse()
{
try
{
JSONArray ja=new JSONArray(jsonData);
JSONObject jo;
realms.clear();
for (int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String name = jo.getString("name");
Log.d("",name);
//realms.add(name);
}
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
And the JSON I am trying to parse into here is:
{
"realms": [{
"type": "pvp",
"population": "low",
"queue": false,
"status": true,
"name": "Aegwynn",
"slug": "aegwynn",
"battlegroup": "Misery",
"locale": "de_DE",
"timezone": "Europe/Paris",
"connected_realms": ["aegwynn"]
}, {
"type": "pve",
"population": "low",
"queue": false,
"status": true,
"name": "Aerie Peak",
"slug": "aerie-peak",
"battlegroup": "Reckoning / Abrechnung",
"locale": "en_GB",
"timezone": "Europe/Paris",
"connected_realms": ["bronzebeard", "aerie-peak"]
}]
(there is more to this but I'd rather not copy it all)
Not sure if perhaps I'm not addressing the "realms" array? Just would appreciate any help on this! As I can't see quite why I'm getting a mismatch?
Kind Regards
J G
Your JSON string show up here it is a JSONObject not a JSONArray, so that you must init an JSONObject with this string, after that get a JSONArray with name realms from previous JSONObject. Here is an example for your reference
This question already has answers here:
How to parse JSON in Java
(36 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
how to directly parse JSONdata using JSONObject in java as my JSON Data don't have any JSONArray .
JSONData:-
{{
"id": 481,
"date": "2016-12-30T13:56:10",
"date_gmt": "2016-12-30T13:56:10",
"guid": {
"rendered": "http://www.mytrendin.com/wp-content/uploads/2016/12/read- 1710011_1280.jpg"
},
"modified": "2016-12-30T13:56:20",
"modified_gmt": "2016-12-30T13:56:20",
"slug": "read-1710011_1280",
"type": "attachment",
"link": "http://www.mytrendin.com/increase-child-development/read-1710011_1280/",
"title": {
"rendered": "child development"
}}
java code
jsonObject = new JSONObject(results);
for(i=0;i<jsonObject.length();i++){
jsonObject=jsonObject.getJSONObject();
j = jsonObject.getString("type");
// mainActivityModel.setId();
}
You json is incorrect.
{
"id": 481,
"date": "2016-12-30T13:56:10",
"date_gmt": "2016-12-30T13:56:10",
"guid": { "rendered": "http://www.mytrendin.com/wp-content/uploads/2016/12/read- 1710011_1280.jpg" },
"modified": "2016-12-30T13:56:20", "modified_gmt": "2016-12-30T13:56:20",
"slug": "read-1710011_1280",
"type": "attachment",
"link": "http://www.mytrendin.com/increase-child-development/read-1710011_1280/", "title": { "rendered": "child development" }
}
You can parse json by this.
JSONObject obj = new JSONObject(result);
JSONObject guid=obj.getJSONObject("guid");
To get json object you will call getJSONObject() and to get String you will call getString()
And if you need to parse a json Array
JSONArray json_arr = new JSONArray(results);
for(i=0;i<json_arr.length();i++){
JSONObject jsonObject=json_arr.getJSONObject(i);
}
go through this tutorial it can help you in understanding json parsing
http://www.technotalkative.com/android-json-parsing/
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
{
"Header": {
"AppId": "appiddfdsf324",
"RecId": "fdsfrecid79878_879898_8797",
"SecureRefId": "fsdf5679567fsd_6789678",
"Type": "Other",
"Ver": "9.0.0",
"StartTS": "2016-09-26:07:48.798798-04:00"
},
"Application": {
"APP_OS": "Windows",
"APP_Runtime": ".Net67986",
"APP_AppName": "MPS",
"APP_AppVersion": "9.0.0.0",
"Host": "fsdhajkfh657895fsdajf",
"Channel": "N/A",
"APP_ReqId": "2f3d7987987-78987-987987-897-da"
},
"Service": {
"Key": "modification process",
"CallType": "HGDL",
"Operation": "processrequest",
"Port": "n/a"
},
"Results": {
"Elapsed": 0,
"Message": "Message Succesfully Deleted",
"TraceLevel": "Information"
},
"Security": {
"Vendor": "abfsdf"
},
"Extended_Fields": {
"CustomerId": "4564987987",
"MessageId": "768789fsdafasdf987987987fasdf",
"TimeElapsed": "1272.8171"
}
}
in above string value we are capturing from website result values we will get in a string format by using selenium webdriver.
This i need to convert and read value of "Message"
Note : i have tried below code
JsonElement jelement = new JsonParser().parse((String) elementText);
JsonObject jobject = jelement.getAsJsonObject();
jobject.getAsJsonObject("Results");
This above will provide complete result value of Result json but i required to fetch values which is present with "Message"
Below first line creates the JSONObject by passing String [which is of JSON format and it should be in JSON format, otherwise it will through an exception]
In Second line , as you have a JSON Object now, you can fetch any element from that,
e.g to fetch the value for Message, which is an element of "Results" object which is of JSON type,
we can access any element by using . and depending on what are you fetching use get
e.g getString -> for getting String,
getInt->for getting Integer,
JSONObject-> for getting an JSONObject
getJSONArray-> for getting a JSONArray
JSONObject jsonObj=new JSONObject(pass your String) //This converts in to JSON Object
jsonObj.getJSONOObject("Results").getString("Message"); //As result internally itself is a JSON Object
I am having the below JSON. Inside this JSON I am having "ticketDetails" as JSON array. From this array I want to retrieve the value of ticketPrice inside the json object "amount". How can I do that?
{
"ticketDetails": [{
"seq": 1,
"qty": 2,
"amount": {
"ticketPrice": 120,
"bookingFee": 50
},
"session": {
"id": 1001,
"date": "2013, 9, 15",
"time": "1300"
},
"venue": {
"id": "MTRG",
"name": "Adlabs Manipur",
"companyCode": "ADLB"
},
"event": {
"id": "ET00000001123",
"name": "Chennai Express",
"producerCode": "YRF"
},
"category": {
"ttypeCode": "00012",
"areaCatCode": "2414",
"type": "Gold",
"price": 270
}
}]
}
Any suggestion will helpful...
Below is the sample code for retrieving the ticketPrice from the given JSONObject:
JSONObject objData = (JSONObject)JSONSerializer.toJSON(data);
JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails");
for(int nSize=0; nSize < objTicketDetailsJsonArr.size(); nSize++){
String ticketPrice = "";
ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice");
}
Below are the imports for the above code:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
source of JAR: http://json-lib.sourceforge.net/
you store your data within a variable
data = {...}
then you access it this way:
data.ticketDetails[0].amount.ticketPrice
if the ticketDetails have more than one element
you can loop over the ticketDetails array and store all the ticketPrice values within an other array, ticketPriceArray
the following would work fine in JavaScript:
var ticketPriceArray = data.ticketDetails.map(function(k){
return k.amount.ticketPrice;
});
if you are using another programming language a general loop would work fine also
for ( i; i< ticketDetails.length ; i++){
ticketPriceArray[i] = data.ticketDetails.amount.ticketPrice[i];
}
For Java check this tutorial:
http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/
you can try this code:
JsonObject transactiondata = (JsonObject)Offer.get("transData");
JsonObject ticketdata = (JsonObject)transactiondata.get("tickets");
JsonObject offerData = (JsonObject)Offer.get("offerData");
JsonObject offerData1 = (JsonObject)offerData.get("offerconfig");
JsonArray jsonarr= (JsonArray)ticketdata.get("ticketDetails");
double ticketPrice = Double.parseDouble(jsonarr.get(0).getAsJsonObject().get("amount").getAsJsonObject().get("ticketPrice").getAsString());
System.out.println("ticketPrice:"+ticketPrice);