This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I'm trying to parse an output from a server that looks like this:
{
"GetFolderFilesByZoneResult": [
{
"ID": 98748,
"CreatedBy": "",
"UpdatedBy": "none",
"CreatedDate": "\/Date(1308273033620+0100)\/",
"UpdatedDate": "\/Date(1308303003770+0100)\/",
"CommentCount": 0,
"Key": "",
"Enabled": true,
"MimeType": "video",
"Votes": 2,
"TotalRating": 0,
"AllowComments": true,
"ViewCount": 323,
"ReleaseDate": "\/Date(1308273000000+0100)\/",
"ExpireDate": "\/Date(4102444800000+0000)\/",
"Author": "",
"Size": 133799936,
"Tag1": "",
"Tag2": "",
"Tag3": "",
"RecycleBin": false
},
{
"ID": 99107,
"CreatedBy": "",
"UpdatedBy": "none",
"CreatedDate": "\/Date(1308583412520+0100)\/",
"UpdatedDate": "\/Date(1308583564007+0100)\/",
"CommentCount": 0,
"Key": "",
"Enabled": true,
"MimeType": "video",
"Votes": 0,
"TotalRating": 0,
"AllowComments": true,
"ViewCount": 33,
"ReleaseDate": "\/Date(1308583380000+0100)\/",
"ExpireDate": "\/Date(4102444800000+0000)\/",
"Author": "",
"Size": 47955968,
"Tag1": "",
"Tag2": "",
"Tag3": "",
"RecycleBin": false
}
]
}
I'm trying to use Java org.json to parse it, but I don't have any experience with JSON/org.json, so I'm having a little trouble. How can I parse this?
1) Assuming you have the JSON libraries on your path (from www.json.org), it's pretty easy.
import org.json.JSONTokener;
...
URI uri = new URI("http://someserver/data.json");
JSONTokener tokener = new JSONTokener(uri.toURL().openStream());
JSONObject root = new JSONObject(tokener);
From there, you can address the various parts of the JSON object. Take a look at the Javadocs for the specifics.
https://developer.android.com/reference/org/json/package-summary.html
Here is the most universal solution, which allows to parse any JSON type into appropriate Java type:
Object json = new JSONTokener(response).nextValue();
Then you can determine resulting type and handle it appropriately.
I'd pass it
map<String, Object>
loaded with
map<String, Object>
in the object field.
Basically recreating the hierarchy of your java classes inside of a large map.
Example :
return ( Map<"GetFolderFilesByZoneResult", Map<"Result1", (object by id 98748) | "Result2", (object by id 99107) | "Result3", etc.
JSON will return that big map very pretty like, and programmatically it's easier to do then lists.
Related
Dears,
I am working on creating a simple method which will take String argument which will be a path or other kind "pointer" to attribute/s in JSON and this method will remove those attribute/s.
My problem is I can find values of those attribute/s using JsonPath, but I can't find methods in rest assured (or other libraries) which could remove/delete attributes by given path.
JSON is already added earlier so i need to pull him from RequestSpecification or FilterableRequestSpecification object ex.
RequestSpecification rs = *objFromContext*;
FilterableRequestSpecification frs= (FilterableRequestSpecification) rs;
frs.getBody();
I've tried to work with JSONObject class and remove() but it doesn't work on complex JSONs.
given example JSON
{
"created": "string",
"updated": "string",
"items": [
{
"code": "TEST",
"nested": {
"code": "test",
"name": "name",
"other": [
{
"code": "TEST",
"name": "myName",
"quantity": 1
}
]
},
"itemsProperties": [
{
"code": "value1",
"name": "name",
"value": 123
}
]
},
{
"code": "TEST",
"nested": {
"code": "test",
"name": "name",
"other": [
{
"code": "TEST",
"name": "myName",
"quantity": 1
}
]
},
"itemsProperties": [
{
"code": "value2",
"name": "name",
"value": 123
}
]
}
],
"timer": {
"startDate": "2015-01-01",
"endDate": "2021-01-02"
},
"id": "myId"
}
using JsonPath jp = JsonPath.from(httpRequest.getBody().toString());
and then jp.get(items.itemsproperties.code) i can find value1 and value2.
I stuck in this point: How to remove those attributes from sended body?
I know i can convert body into JSONObject and then go field after field conversion between getJSONArray and GetJSONOBject and remove those fields, but i would like to make this metod much more universal.
Is this possible?
If you want to manipulate json in Rest-Assured JsonPath, then the answer is No. You can't do that. JsonPath help you to extract value from json, that's it, no more.
You have to use different libraries to remove key-value pair.
For example: using JsonPath Jayway
DocumentContext parse = JsonPath.parse(body);
parse.delete("$..itemsProperties..code");
System.out.println(parse.jsonString());
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
"sport_events": [
{
"id": "sr:match:12606716",
"scheduled": "2017-09-27T10:00:00+00:00",
"start_time_tbd": false,
"status": "closed",
"tournament_round": {
"type": "group",
"number": 1,
"group": "Gr. 4"
},
"season": {
"id": "sr:season:45960",
"name": "U17 European Ch.ship QF 17/18",
"start_date": "2017-09-27",
"end_date": "2018-04-30",
"year": "17/18",
"tournament_id": "sr:tournament:755"
},
"tournament": {
"id": "sr:tournament:755",
"name": "U17 European Ch.ship QF",
"sport": {
"id": "sr:sport:1",
"name": "Soccer"
},
"category": {
"id": "sr:category:392",
"name": "International Youth"
}
},
"competitors": [
{
"id": "sr:competitor:22646",
"name": "Russia",
"country": "Russia",
"country_code": "RUS",
"abbreviation": "RUS",
"qualifier": "home"
},
{
"id": "sr:competitor:22601",
"name": "Faroe Islands",
"country": "Faroe Islands",
"country_code": "FRO",
"abbreviation": "FRO",
"qualifier": "away"
}
]
},
Add gson to your project by adding this into your build-script.gradle:
dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}
Now create the classes you need but first correct your json string. I guess you forgot a attributename at the beginning. This is your new best friend: json formatter online
After you corrected your json-string and you´ve created your Wrapper and Pojo model-classes with the needed attributes, you parse the string back into the wrapper-object and with getter/setter you get change/get data out of it.
Gson gson = new GsonBuilder().create();
Wrapper wrap = gson.fromJson(jsonString, Wrapper.class);
Don´t forget try-catch block because there can be many thrown exceptions.
Good luck to you.
How-to-for-beginner
Im requesting data from instagram api when I search for any tag. In return I get a massive chunk of json data corresponding to like 20 pictures. The response below is the chunk I used to generate my pojos online
{
"pagination": {
"next_max_tag_id": "1193052000552992097",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "1193052000552992097",
"next_min_id": "1193052554319844057",
"min_tag_id": "1193052554319844057",
"next_url": "https://api.instagram.com/v1/tags/cats/media/recent?access_token=631477962.1fb234f.f7c5cda97c7f4df983b1c764f066ed37&max_tag_id=1193052000552992097"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"cats",
"caseworker",
"homestuck"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Normal",
"created_time": "1456442969",
"link": "https://www.instagram.com/p/BCOkvoim1LZ/",
"likes": {
"count": 0,
"data": []
},
"images": {
"low_resolution": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 320,
"height": 320
},
"thumbnail": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1456442969",
"text": "Bitch! I'm fabulous! That's my case worker..she is obsessed with cats\n\n#cats #caseworker #homestuck",
"from": {
"username": "strider_inc",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12558836_953196128050469_1739102_a.jpg",
"id": "2322171747",
"full_name": "WE All 4EVER KAWAII TRASH GODS"
},
"id": "1193052563471815092"
},
"user_has_liked": false,
"id": "1193052554319844057_2322171747",
"user": {
"username": "strider_inc",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12558836_953196128050469_1739102_a.jpg",
"id": "2322171747",
"full_name": "WE All 4EVER KAWAII TRASH GODS"
}
}
So when I do that I get like 10-12 different pojo classes into which I should map this data. Now firstly...Im just trying that out and Im 100% Ill have some problem mapping them I mean gson will do it for me but i dont know if there are any more that I would need etc.
but most importantly my app only needs the low standard url pictures all the other information is useless for me.
Ofcourse, I know one way to do it which is to convert the whole thing into a string and parse the whole string through multiple times looking for key words etc and making images etc. I dont want to do that because its ugly. It works but I want a concise way of doing that at the same time without mapping completely.
Using Gson's JsonParser class, you can parse your JSON into a tree of JsonElements, and then extract just the data that you need.
For example, in order to print out all the low resolution URLs, you could use the following code:
String json = "...";
JsonParser parser = new JsonParser();
JsonObject object = parser.parse(json).getAsJsonObject();
JsonArray data = object.getAsJsonArray("data");
for (JsonElement element : data) {
JsonObject images = element.getAsJsonObject().getAsJsonObject("images");
JsonObject lowResolution = images.getAsJsonObject("low_resolution");
String url = lowResolution.getAsJsonPrimitive("url").getAsString();
System.out.println(url);
}
Using your example JSON, this would print:
https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2
I am developing first time in android and i have never used json data before. I will develop an application of event calendar of my university. We developed web version application in Django and we implement tastypie (restapi) so i need to use this json data for android mobile version. My json data is like this :
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 5
},
"objects": [{
"Location": "Z011",
"Notes": "asdf",
"Title": "Literature Talking",
"id": 3,
"resource_uri": "/api/v1/Events/3/"
}, {
"Location": "Batı Kampüsü, Sinema Salonua",
"Notes": "sd",
"Title": "TARİHÇE KONFERANSLARI SERİSİ 25",
"id": 4,
"resource_uri": "/api/v1/Events/4/"
}, {
"Location": "in Campus",
"Notes": "afafdf",
"Title": "Self-Assessment Project",
"id": 5,
"resource_uri": "/api/v1/Events/5/"
}, {
"Location": "Kütüphane",
"Notes": "fs",
"Title": "51.Kütüphane Haftası",
"id": 6,
"resource_uri": "/api/v1/Events/6/"
}]
}
how can I parse this Json data in android studio?
Using below code you will be able to get Title and Location
JSONObject obj=new JSONObject(response);//This is response from webservice
String totalCount = obj.getJSONObject("meta").getString("total_count"); //for getting total_count
JSONArray json_array = obj.getJSONArray("objects");
for(int j=0;j<json_array.length();j++) {
String title = json_array.getJSONObject(j).getString("Title");
String location= json_array.getJSONObject(j).getString("Location");
}
Use this website to help you view the Json structure better
http://www.jsontree.com/
What you have is a Json Object since it starts and ends with curly braces.
For example if I had a Json as {"Id":"1"}
The Key is "Id" and the value is "1"
A Json object can have a Json inside the value as well(Which is your case)
And example is {"Id":{"Place1":"1", "Place2":"2"}}
So the Key is "Id" and it has the value "Place1":"1", "Place2":"2"
So the value is also a Json.
It can get a little messy with Jsons in Jsons.
Here is a good tutorial on parsing Json
http://www.tutorialspoint.com/android/android_json_parser.htm
at the moment I'm parsing the string with eval()-method and it works fine, but want to parse it with the native JSON methods of a browser. Is there good way to parse the string with jquery.parseJSON() or with any other jQuery method to an array of javascript objects? The string looks like
[
{
"title": "01 Books",
"groupId": "01",
"groupName": "Books",
"key": "1",
"isFolder": true,
"expand": false,
"isLazy": true
},
{
"title": "02 Music",
"groupId": "02",
"groupName": "Music",
"key": "2",
"isFolder": true,
"expand": false,
"isLazy": true
}
]
build with net.sf.json.JSONArray of Java.
jquery.parseJSON() can just parse strings like {"Key":"Value","Key":"Value",....} I guess?
thx for your help!
You have a typo. It is jQuery, not jquery. Capitalization is important.
jQuery.parseJSON()
or
$.parseJSON()
This is supposed to parse it into a json object.