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);
Related
I want to return the class at the same level here.
As here id, username, password, etc are under userCredentialEntity and so in userDetailEntity key.
{
"userCredentialsEntity": {
"id": 5,
"username": "testuser3",
"password": "$2a$10$yFmeUcE3uTOf9H4TZqWXfO/b8zsTp6sqnWax5iyRXBhlfXF3dSsk2",
"email": "testuser3#gmail.com",
"roles": [
{
"id": 2,
"name": "ROLE_MANAGER"
}
]
},
"userDetailsEntity": {
"userId": 5,
"first_name": "Test",
"last_name": "Singh 3",
"birth_date": "12",
"birth_month": "01",
"birth_year": "2002",
"area": "Chandani Chowk",
"city": "Sahadra",
"district": "Sonbhadra",
"pin_code": 231325,
"mobile_number": "6788762345"
}
}
I have to return this.
{
"id": 5,
"username": "testuser3",
"email": "testuser3#gmail.com",
"roles": [
{
"id": 2,
"name": "ROLE_MANAGER"
}
],
"first_name": "Test",
"last_name": "Singh 3",
"birth_date": "12",
"birth_month": "01",
"birth_year": "2002",
"area": "Chandani Chowk",
"city": "Sahadra",
"district": "Sonbhadra",
"pin_code": 231325,
"mobile_number": "6788762345"
}
And also neglect the password and userId field while returning
The Code for my implementation is:
#Data
public class UserMerged {
private UserCredentialsEntity userCredentialsEntity;
private UserDetailsEntity userDetailsEntity;
}
UserDetailsEntity userDetailsEntity = userDetailService.fetchUserDetails(userId).get();
UserCredentialsEntity userCredentialsEntity = userCredentialsRepository.findByUsername(username);
UserMerged userMerged = new UserMerged();
userMerged.setUserDetailsEntity(userDetailsEntity);
userMerged.setUserCredentialsEntity(userCredentialsEntity);
return ResponseEntity.ok().body(userMerged);
I am new in Spring Boot and doesn't got any satisfactory answer regarding this. Please suggest me any way of achieving this.
Thank You.
First thing first, Whatever your return type of object is, for that you need to create the specific class and then return it.
In your case Modify your UserMerged class with whatever u would like to return and then set the parameters accordingly.
Likely,
Your UserMerged will be
#Data
public class UserMerged {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer Id;
#Column(name="username")
private String username;
#Column(name="email")
private String email;
#Column(name="roles")
private List<Roles> roles;
#Column(name="first_name")
private String first_name;
#Column(name="last_name")
private String last_name;
#Column(name="birth_date")
private String birth_date;
#Column(name="birth_month")
private String birth_month;
#Column(name="birth_year")
private String birth_year;
#Column(name="area")
private String area;
#Column(name="city")
private String city;
#Column(name="district")
private String district;
#Column(name="pin_code")
private Integer pin_code;
#Column(name="mobile_number")
private Integer mobile_number;
And instead of setting the UserDetailsEntity and UserCredentialsEntity you can set your fields from those two classes to UserMerged class.
userMerged.setId(userCredentialsEntity.getId());
userMerged.setUsername(userCredentialsEntity.getUsername());
userMerged.setEmail(userCredentialsEntity.getEmail());
userMerged.setRoles(userCredentialsEntity.getRoles());
userMerged.setFirst_name(userDetailsEntity.getFirst_name());
userMerged.setLast_name(userDetailsEntity.getLast_name());
userMerged.setBirth_date(userDetailsEntity.getBirth_date());
userMerged.setBirth_month(userDetailsEntity.getBirth_month());
userMerged.setBirth_year(userDetailsEntity.getBirth_year());
userMerged.setArea(userDetailsEntity.getArea());
userMerged.setCity(userDetailsEntity.getCity());
userMerged.setDistrict(userDetailsEntity.getDistrict());
userMerged.setPin_code(userDetailsEntity.getPin_code());
userMerged.setMobile_number(userDetailsEntity.getMobile_number());
This will set all parameters you needed, and you can return the object of user merged object.
Here Their is lot much repetation of code exist so instead so please take care of that or you can also add common parameters into one class.
I got a null object attributes after deserialization of a json response.
Developing under android, I'm using retrofit2 , moshi as converter (https://github.com/kamikat/moshi-jsonapi ) .
When debugging ,I saw a json response fully retrieved (not null attributes),but deserialization fails. Should I use GSON instead?
Here's my retrofit builder I use to make my json call: (no issue)
public static JsonServerInterface getSimpleClient(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_AUTH_URL)a
.addConverterFactory(MoshiConverterFactory.create())
.build();
JsonServerInterface webServer=retrofit.create(JsonServerInterface.class);
return webServer;
}
My api json call,response contain UserModel with null attributes(deserialization fails without any error)
signInCall.enqueue(new Callback<UserModel>(){
#Override
public void onResponse
(Call<UserModel> call, Response<UserModel> response)
{
response.message();
}
}
My UserModel (as required by moshi ,but I think it lacks something):
#JsonApi(type = "users")
public class UserModel extends Resource {
#Json(name = "auth-token")
private String authToken;
#Json(name = "firstname")
private String firstname;
#Json(name = "lastname")
private String lastname;
#Json(name = "email")
private String email;
#Json(name = "created-at")
private String createdAt;
#Json(name = "updated-at")
private String updatedAt;
private HasMany<ActivityModel> activities;
My json response I saw when debugging http response, I retrieve without any trouve,but moshi sucks to deserialize it,and no errors are raised:
{
"data": {
"id": "21",
"type": "users",
"attributes": {
"auth-token": "t8S3BTqyPwN3T4QDMY1FwEMF",
"firstname": "aymen",
"lastname": "myself",
"email": "aymen.myself#gmail.com",
"created-at": "2017-11-13T22:52:39.477Z",
"updated-at": "2017-11-13T23:21:09.706Z"
},
"relationships": {
"activities": {
"data": [
{
"id": "81",
"type": "activities"
}
]
}
}
},
"included": [
{
"id": "81",
"type": "activities",
"attributes": {
"title": "activity 10",
"description": "how to draw a circle",
"start-at": "2017-11-13T23:06:13.474Z",
"duration": 10,
"created-at": "2017-11-13T23:06:32.630Z",
"updated-at": "2017-11-13T23:06:32.630Z"
},
"relationships": {
"user": {
"data": {
"id": "21",
"type": "users"
}
}
}
}
]
}
I find the solution after lot of hours:
I should use "Document" instead of UserModel
interface:
#POST("sign-in.json")
Call<Document> signIn(#Body Credentials credentials);
when calling:
signInCall.enqueue(new Callback<Document>(){
#Override
public void onResponse(Call<Document> call, Response<Document> response) {
hope it helps
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
i have the following json string
{
"Count": 10,
"Page": 0,
"Queue": [
{
"id": "146648",
"number": "96599004970"
},
{
"id": "146647",
"number": "96599004970"
},
{
"id": "146646",
"number": "96599004970"
},
{
"id": "146645",
"number": "96599004970"
},
{
"id": "146644",
"number": "96599004970"
},
{
"id": "146643",
"number": "96599004970"
},
{
"id": "146642",
"number": "96599004970"
},
{
"id": "146641",
"number": "96599004970"
},
{
"id": "146640",
"number": "96599004970"
},
{
"id": "146639",
"number": "96599004970"
}
]
}
i'm using vb.net with newtonstoft json
i made these classes
Public Class Queue
Public Property Count As Integer
Public Property Page As Integer
Public Property Msgs As List(Of Msg)
End Class
Public Class Msg
Public Property id As String
Public Property number As String
End Class
I used this code to deserialize this string
Dim getQueue as Queue
getQueue = JsonConvert.DeserializeObject(Of Queue)(jsonString)
how can i rebuild the array? or retreive data from that queue object
any help is appreciated
To make your json string deserialized properly, your mapping class should look like this instead :
Public Class RootObject
Public Property Count As Integer
Public Property Page As Integer
Public Property Queue As List(Of Queue)
End Class
Public Class Queue
Public Property id As String
Public Property number As String
End Class
Then you can do as follow :
Dim getQueue as RootObject
getQueue = JsonConvert.DeserializeObject(Of RootObject)(jsonString)
For Each Q As Queue In getQueue.Queue
'here you can access each Queue object
Next
NB: above class definitions are translated from C# classes generated using http://json2csharp.com/ tool. That is a handy online tool to generate classes suitable for mapping your json.
The following code prints id and number values for each msgs:
For Each msg As Msg In getQueue.Msgs
Console.WriteLine("id: " + msg.id & ", number: " + msg.number)
Next
try this. Sorry its in C# as I dont know VB.net
var JsonStr = JsonConvert.DeserializeObject<Queue>(jsonString);
label1.Text = JsonStr.Count
label2.Text = JsonStr.Page
for (int i = 0; i < JsonStr.Msg.Count; i++)
{
label3.Text = JsonStr.Msg[i].id;
label4.Text = JsonStr.Msg[i].number;
}
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