I'd like to deserialize this using GSON into a list of Post, but can't figure out how to tell GSON how to ignore the root element "posts" (as its an object) and just process the array.
I've got:
Type postTypeList = new TypeToken<List<Post>>(){}.getType();
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(myJSONString);
JsonObject postsRootObj = jsonElement.getAsJsonObject();
List<Post> postList = gson.fromJson(postsRootObj.get("posts"), postTypeList);
BUT.. I'd rather not have the whole JsonParser, I'd rather just pass it directly into the gson.fromJson function.. Is there a way to do this?
{ "posts":
[
{
"username": "John",
"message": "I'm back",
"time": "2010-5-6 7:00:34"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
,
{
"username": "Smith",
"message": "I've been waiting",
"time": "2010-4-6 10:30:26"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
]}
Create a wrapper class which will have List<Post> as its member
public class PostList{
private List<Post> posts;
// getter and setters for posts
}
And then use fromJson in the similar fashion
List<Post> postList = gson.fromJson(myJSONString,PostList.class);
There is a correction from above. Usage should be :
PostList postList = gson.fromJson(myJSONString,PostList.class);
Post post = postlist.get(index) //index is the index of list you want to access
Related
i want to get avatar_url in actor object. i can get "id" and "type" to show in recyclerview. but avatar_url not show image why?
json url
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for(int i=0; i<response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Article article = new Article();
article.setAvatar_url(jsonObject.getString("avatar_url"));
article.setId(jsonObject.getString("id"));
article.setType(jsonObject.getString("type"));
articles.add(article);
how i get avatar_url from actor field?
and yes i can run because i delete
article.setAvatar_url(jsonObject.getString("avatar_url"));
Thanks
Looking at your JSON, you can see that the "avatar_url" isn't a peer of the "id" and "type".
"id": "11392115556",
"type": "PushEvent",
"actor": {
"id": 8517910,
"login": "LombiqBot",
"display_login": "LombiqBot",
"gravatar_id": "",
"url": "https://api.github.com/users/LombiqBot",
"avatar_url": "https://avatars.githubusercontent.com/u/8517910?"
},
You need to retrieve the "actor" object and then get the "avatar_url" from within that object.
I have a JSON Response and want to extract list of values from response for e.g all the values of id's present.
{
"page": 2,
"per_page": 3,
"total": 12,
"total_pages": 4,
"data": [
{
"id": 4,
"first_name": "Eve",
"last_name": "Holt",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
},
{
"id": 5,
"first_name": "Charles",
"last_name": "Morris",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"
},
{
"id": 6,
"first_name": "Tracey",
"last_name": "Ramos",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"
}
]
}
I have tried below code but not able to achieve but it is only printing first value of id i.e 4.
public class Get_Request {
public static void main(String[] args) {
RestAssured.baseURI = "https://reqres.in/";
Response res = given()
.param("page", "2")
.when()
.get("/api/users")
.then()
.assertThat()
.contentType(ContentType.JSON)
.and()
.statusCode(200).extract().response();
/*String data = res.jsonPath().getString("data[0].first_name");
System.out.println(data);
*/
List<HashMap<String,Object>> allids = res.jsonPath().getList("data");
HashMap<String,Object> firstid = allids.get(0);
Object a = firstid.get("id");
System.out.println(a);
}
}
I am beginner in rest assured also i am not sure whether we can achieve the same. Any help would be appreciated. Thanks in advance.
Below Code will find all the ids present in the Response and it will print the result like 4 5 6
List<Integer> ids = res.jsonPath().getList("data.id");
for(Integer i:ids)
{
System.out.println(i);
}
That can be done by changing your path to data.id
List<Integer> ids = res.jsonPath().getList("data.id");
Integer id = ids.get(0);
You can use JsonPath wildcards to extracts data from response , which will save you from writing code everytime you have such requirement, use below JsonPath to extract list of Ids from your response :
$..id
I have a json like this, which i am getting in the response from http call
{
"offset": 0,
"limit": 50,
"objects": [
{
"id": "59118fb6e4b0168ec4b56692",
"modifiedDate": 1494323126886,
"requestedIds": null,
"mergedIds": [],
"properties": {
"name": [
{
"value": "Abhimanyu",
"metadata": {}
}
],
"company": [],
"title": [],
"email": [
{
"value": "absinghrathore127#gmail.com",
"metadata": {}
}
]
},
"state": "ACTIVE"
},
{
"id": "590d5813e4b03a8336fa1642",
"modifiedDate": 1494046739619,
"requestedIds": null,
"mergedIds": [],
"properties": {
"name": [
{
"value": "Tim Archer",
"metadata": {}
}
],
"company": [],
"title": [],
"email": [
{
"value": "tim#avocado.com",
"metadata": {}
}
]
},
"state": "ACTIVE"
}
],
"size": 2
}
and i am able to get objects from json via this following code :
String s = res.getBody();
Map<String,Object> jsonMap = (Map<String, Object>)JSON.deserializeUntyped(s);
String jsonSubset = JSON.serialize(jsonMap.get('objects'));
What i need is the value of name and email in some variable.
Please help me out in this!!
This is going to be a tedious task but once you've classified your all data into appropriate Wrapper classes then it's fairly simple and easy to maintain.
First thing is to define your MainWrapper class. This will contain all the at it's own level. If it has any Object as key-pair then we need to make sure to include it as a List<>. So This is how your MainWrapper should be:
public class MainWrapper {
Integer offset; // Singleton variable
Integer limits; // Singleton variable
List<ObjectsWrapper> objects; // Collection variable since it starts with [],
Integer size; // Singleton variable
}
Since you've array of objects in JSON that's why I've included it as a List in MainWrapper. Now it's time to define ObjectsWrapper. Below is wrapper defined for the same.
public class ObjectsWrapper {
String id;
String modifieddate;
String requestedIds;
PropertyWrapper properties;
}
Since there is only on properties associated with objects that's why it's a non-collection type. Below is representation of properties.
public class PropertyWrapper {
List<NameWrapper> name;
List<String> company;
List<String> title;
List<EmailWrapper> email;
String state;
}
public class NameWrapper {
String name;
String metadata;
}
I guess now you've a fair idea of how to organize data of JSON into various wrapper class. Once you're done with this, simply deserialize the JSON into MainWrapper class and access it.
For example:
MainWrapper mainJSONWrapper = (MainWrapper) JSON.deserialize(JSON,MainWrapper.class);
List<ObjectsWrapper> objectsLst = mainJSONWrapper.objects;
for(ObjectsWrapper obj:objectsLst) {
List<NameWrapper> lstNameWrapper = obj.properties;
for(NameWrapper nameObj:NameWrapper) {
System.debug('Name:'+nameObj.name);
System.debug('metadata:'+nameObj.metadata);
}
}
Above code is not tested but yes, it will give idea how you should deserialize JSON in appropriate manner.
Also go through this answer..How to deserialize a JSON String to Apex
The response of my service ALFRESCO REST is:
[
{
"role": "SiteManager",
"authority":
{
"authorityType": "USER",
"fullName": "admin",
"userName": "admin",
"firstName": "Administrator",
"lastName": "",
"url": "\/alfresco\/service\/api\/people\/admin"
},
"url": "\/alfresco\/service\/api\/sites\/test3\/memberships\/admin"
}
,
{
"role": "SiteConsumer",
"authority":
{
"authorityType": "GROUP",
"shortName": "jamalgg",
"fullName": "GROUP_jamalgg",
"displayName": "jamalgg",
"url": "\/alfresco\/service\/api\/groups\/jamalgg"
},
"url": "\/alfresco\/service\/api\/sites\/test3\/memberships\/GROUP_jamalgg"
}
,
{
"role": "SiteManager",
"authority":
{
"authorityType": "GROUP",
"shortName": "ALFRESCO_ADMINISTRATORS",
"fullName": "GROUP_ALFRESCO_ADMINISTRATORS",
"displayName": "ALFRESCO_ADMINISTRATORS",
"url": "\/alfresco\/service\/api\/groups\/ALFRESCO_ADMINISTRATORS"
},
"url": "\/alfresco\/service\/api\/sites\/test3\/memberships\/GROUP_ALFRESCO_ADMINISTRATORS"
}
]
And I want to parse to list of object:
List<Memberships > listMemberships;
public class Memberships {
private String role;
private List<Authority> listAuthority ;
private String url;
}
public class Authority {
private String authorityType;
private String shortName;
private String fullName;
private String displayName;
private String url;
}
I think that there are two solutions:
how to add the tag Memberships to JSON result for encapsulates
the whole.
how to parse JSON result directly to my list
Thanks
As answered in a-better-java-json-library I would use the google-gson library.
Thank you Ozoli. The answer to my question is:
Type targetType = new TypeToken<Collection<Memberships>>() {}.getType();
List<Memberships> list = (List<Memberships>) new Gson().fromJson(renduJson,targetType);
You can also use http://jsongen.byingtondesign.com/ to generate java code from json response and then use jackson library ( http://jackson.codehaus.org/ ) to bind that response data to your object(s):
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);
sorry for not formatting code
Type targetType = new TypeToken<Collection<Memberships>>() {}.getType();
List<Memberships> list = (List<Memberships>)new Gson().fromJson(rendu,targetType);
I'm fairly new to programming, and I'm an intern working to develop a Blackberry App. So, I apologize in advance if I use any wrong terminology.
I make a HTTP Request for all of the friends of a particular user, and get a JSON response in this JSON array format.
{"users": [{"username": "jonbob", "first_name": "Jon", "last_name": "Bob", "phone": "5555555555", "full_name": "Jon Bob", "id": 1}, {"username": "joesmith", "first_name": "Joe", "last_name": "Smith", "phone": "5555555555", "full_name": "Joe Smith", "id": 2}]}
I'm using the org.json parsing library. I'm trying to create a Blackberry list containing all of the User's Friends (like an address book). But I am unsure how to acess the JSON Array with this org.json library. I want to create a Java Array with only the full_names of all the friends. How would you go about parsing this response to accomplish that?
Thanks
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
public class Foo
{
public static void main(String[] args) throws Exception
{
/*
{
"users": [
{
"username": "jonbob",
"first_name": "Jon",
"last_name": "Bob",
"phone": "5555555555",
"full_name": "Jon Bob",
"id": 1
},
{
"username": "joesmith",
"first_name": "Joe",
"last_name": "Smith",
"phone": "5555555555",
"full_name": "Joe Smith",
"id": 2
}
]
}
*/
String json = "{\"users\": [{\"username\": \"jonbob\", \"first_name\": \"Jon\", \"last_name\": \"Bob\", \"phone\": \"5555555555\", \"full_name\": \"Jon Bob\", \"id\": 1}, {\"username\": \"joesmith\", \"first_name\": \"Joe\", \"last_name\": \"Smith\", \"phone\": \"5555555555\", \"full_name\": \"Joe Smith\", \"id\": 2}]}";
JSONObject result = new JSONObject(json);
JSONArray users = result.getJSONArray("users");
int size = users.length();
Friend[] friends = new Friend[size];
for (int i = 0; i < size; i++)
{
JSONObject user = users.getJSONObject(i);
friends[i] = new Friend(user.getString("first_name"), user.getString("last_name"));
}
System.out.println(Arrays.toString(friends));
// output: [Jon Bob, Joe Smith]
}
}
class Friend
{
String firstName;
String lastName;
Friend (String f, String l) {firstName = f; lastName = l;}
#Override
public String toString() {return String.format("%s %s", firstName, lastName);}
}
You can have a look at GSon this library is powerful for json and java manipulation.
List<Users> users= gson.fromJson(json, new TypeToken<List<Users>>(){}.getType());
Here is the API doc.
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html