Related
How to deserialize below JSON?
When i am using below code
Response response=engine.getResponse(Method.GET,strURL,strBAUsername,strBAPassword,null,ContentType.JSON);
userEdit=response.as(TestUserRoleInfoList.class); // TestUserRoleInfoList is a POJO class
#JsonIgnoreProperties(ignoreUnknown=true)
public class TestUserRoleInfoList {
#JsonProperty("userRoleInfoList")
List<UserRoleInfo> userRoleInfo=new ArrayList<UserRoleInfo>();
public List<UserRoleInfo> getUserRoleInfo() {
return userRoleInfo;
}
public void setUserRoleInfo(List<UserRoleInfo> userRoleInfo) {
this.userRoleInfo = userRoleInfo;
}
}
Somehow it unable to parse Regions internal class. But i am least bothered. I need collectionRole fields.
How can i get the list of collection roles?
{
"id": 5595,
"userName": "abc",
"firstName": "abc",
"lastName": "ijk",
"additionalName": "Ernest",
"namePrefix": {
"id": null,
"prefix": null,
"createdAt": null,
"updatedAt": null
},
"nameSuffix": {
"id": null,
"suffix": null,
"createdAt": null,
"updatedAt": null
},
"emplId": "11111",
"workDayId": "11111",
"staffEmailAddress": null,
"facultyEmailAddress": "abc.xyz#xxxx.edu",
"userRoleInfoList": [
{
"userId": 5595,
"collectionRole": "program-chair",
"regions": [
{
"id": 1,
"region": "Germany 1",
"regionalDirectorFirstName": "aaaa",
"regionalDirectorLastName": "bbbb",
"associateDirectorFirstName": null,
"associateDirectorLastName": null,
"division": {
"id": 2,
"name": "Europe",
"deletedFlag": false,
"createdAt": null,
"updatedAt": null
},
"deletedFlag": false,
"createdAt": null,
"updatedAt": null
}
],
"school": {
"id": 3,
"name": "Arts and Sciences",
"dean": null,
"createdAt": null,
"updatedAt": null
},
"facultyPhoto": null,
"primary": false
},
{
"userId": 5595,
"collectionRole": "faculty",
"regions": [
{
"id": 3,
"region": "Germany 1",
"regionalDirectorFirstName": "aaaa",
"regionalDirectorLastName": "bbbb",
"associateDirectorFirstName": null,
"associateDirectorLastName": null,
"division": {
"id": 2,
"name": "Europe",
"deletedFlag": false,
"createdAt": null,
"updatedAt": null
},
"deletedFlag": false,
"createdAt": null,
"updatedAt": null
}
],
"school": {
"id": 3,
"name": "Arts and Sciences",
"dean": null,
"createdAt": null,
"updatedAt": null
},
"facultyPhoto": null,
"primary": true
}
]
}
You can use org.json.JSONObject
Response response = when()
.get("api_url")
.then()
.extract().response();
JSONObject jsonObject = new JSONObject(response.getBody().asString());
JSONArray jsonArray = jsonObject.getJSONArray("userRoleInfoList");
List<String> stringList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
stringList.add(jsonArray.getJSONObject(i).getString("collectionRole"));
}
System.out.println(stringList);
This will output [program-chair, faculty]
My database is structured as below
public partial class AspNetUserMessage
{
public string From { get; set; }
public string To { get; set; }
public string Text { get; set; }
public System.DateTime SentDate { get; set; }
public Nullable<System.DateTime> ReadDate { get; set; }
public int Id { get; set; }
}
I have an API point which returns all the messages sent by a user e.g
[
{
"From": "0617c281-5488-4009-bf37-761f6cfea2df",
"To": "f54b7bf4-c7b5-482c-83b8-5b61e78ea398",
"Text": "i love this backend!!",
"SentDate": "2020-04-10T00:00:00",
"ReadDate": "2020-04-10T00:00:00",
"Id": 1
},
{
"From": "0617c281-5488-4009-bf37-761f6cfea2df",
"To": "f54b7bf4-c7b5-482c-83b8-5b61e78ea398",
"Text": "this is a sample msg",
"SentDate": "0001-01-01T00:00:00",
"ReadDate": null,
"Id": 2
},
{
"From": "0617c281-5488-4009-bf37-761f6cfea2df",
"To": "f54b7bf4-c7b5-482c-83b8-5b61e78ea398",
"Text": "id test",
"SentDate": "0001-01-01T00:00:00",
"ReadDate": null,
"Id": 3
},
{
"From": "0617c281-5488-4009-bf37-761f6cfea2df",
"To": "f54b7bf4-c7b5-482c-83b8-5b61e78ea398",
"Text": "blocked test",
"SentDate": "0001-01-01T00:00:00",
"ReadDate": null,
"Id": 4
},
{
"From": "0617c281-5488-4009-bf37-761f6cfea2df",
"To": "f54b7bf4-c7b5-482c-83b8-5b61e78ea398",
"Text": "blocked other way test",
"SentDate": "0001-01-01T00:00:00",
"ReadDate": null,
"Id": 5
},
{
"From": "0617c281-5488-4009-bf37-761f6cfea2df",
"To": "f54b7bf4-c7b5-482c-83b8-5b61e78ea398",
"Text": "date test",
"SentDate": "2020-04-11T00:00:00",
"ReadDate": null,
"Id": 6
},
{
"From": "0617c281-5488-4009-bf37-761f6cfea2df",
"To": "f54b7bf4-c7b5-482c-83b8-5b61e78ea398",
"Text": "date test",
"SentDate": "2020-04-11T00:00:00",
"ReadDate": null,
"Id": 7
},
{
"From": "0617c281-5488-4009-bf37-761f6cfea2df",
"To": "f54b7bf4-c7b5-482c-83b8-5b61e78ea398",
"Text": "id test",
"SentDate": "0001-01-01T00:00:00",
"ReadDate": null,
"Id": 8
},
{
"From": "0617c281-5488-4009-bf37-761f6cfea2df",
"To": "f54b7bf4-c7b5-482c-83b8-5b61e78ea398",
"Text": "id test",
"SentDate": "0001-01-01T00:00:00",
"ReadDate": null,
"Id": 9
}
]
My code is the following:
public IEnumerable<AspNetUserMessage> GetAllMessages([FromBody]MessageRequest Request)
{
try
{
// Get all the messages sent or received by the user
var messages = db.AspNetUserMessages.Where(o => o.From == Request.From || o.To == Request.From).ToList();
return messages;
}
catch (Exception e)
{
// Log the error to the database
LogException(e);
return null;
}
}
What I want to do is instead of returning all the messages, I want to return a categorized version of the messages. E.g
User1 sent 4 messages to User2;
User1 sent 2 messages to User3
For user1 output should be
[
{
"SentTo": "User2"
"Messages": [All 4 Messages sent to User2 here]
},
{
"SentTo": "User3"
"Messages": [All 2 Messages sent to User3 here]
}
]
How can I achieve this modifying my GetAllMessages function
You have to make a a new model that uses your AspNetUserMessage and fill it.
Make a new model, for now I named it SentMessagesModel
public class SentMessagesModel{
public string SentTo {get;set;}
public List<AspNetUserMessage> Messages {get;set;}
// All 4 Messages sent to User2 here
}
Then make a new controller action that uses the new model. Use the code below
public List<SentMessagesModel> GetAllMessages([FromBody]MessageRequest Request)
{
try
{
// Get all the messages sent or received by the user
var messages = db.AspNetUserMessages.Where(o => o.From == Request.From).ToList();
var groupByTo = messages.GroupBy(m=>m.To);
List<SentMessagesModel> sentMessages = new List<SentMessagesModel>();
foreach(var currentGroup in groupByTo){
sentMessages.Add(new SentMessagesModel(){ SentTo = currentGroup.Key, Messages = currentGroup.ToList() })
}
return sentMessages;
}
catch (Exception e)
{
// Log the error to the database
LogException(e);
return null;
}
}
I used Create Call of Microsoft Graph API to create a group call(audio). The connection has created successfully, but every member cannot receive any chat message posted by other members.
(picture)The phenomenon that everyone cannot receive other's message
Request as below:
POST https://graph.microsoft.com/beta/app/calls
Content-Type: application/json
Authorization: Bearer <Token>
{
"#odata.type": "#microsoft.graph.call",
"callbackUri": "https://myhostname.ngrok.io/callback/calling",
"mediaConfig": {
"#odata.type": "#microsoft.graph.serviceHostedMediaConfig"
},
"source": {
"identity": {
"application": {
"id": "myCallingAppId"
}
}
},
"subject": "Test Call",
"targets": [
{
"identity": {
"user": {
"id": "User_1-Id",
"displayName": "User_1-DisplayName"
}
},
"identity": {
"user": {
"id": "User_2-Id",
"displayName": "User_2-Name"
}
}
}
],
"tenantId": "myCallingAppTenant"
}
Response:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#communications/calls/$entity",
"id": "481f0c00-ffff-41cd-bbc8-7e21fb5e8b1b",
"state": "establishing",
"transferState": null,
"terminationReason": null,
"direction": "outgoing",
"ringingTimeoutInSeconds": null,
"subject": "Test Call",
"callbackUri": "https://myhostname.ngrok.io/callback/calling",
"requestedModalities": [],
"activeModalities": [],
"routingPolicies": [],
"tenantId": "myCallingAppTenant",
"myParticipantId": "59e11e38-87d0-4ae5-b3ce-051ea26aa34d",
"mediaState": null,
"resultInfo": null,
"answeredBy": null,
"chatInfo": null,
"meetingInfo": null,
"meetingCapability": null,
"toneInfo": null,
"incomingContext": null,
"callRoutes": [],
"source": {
"region": null,
"languageId": null,
"identity": {
"user": null,
"device": null,
"phone": null,
"application": {
"id": "myCallingAppId",
"displayName": null
}
}
},
"targets": [
{
"region": null,
"languageId": null,
"identity": {
"application": null,
"device": null,
"phone": null,
"user": {
"id": "User_1-Id",
"displayName": "User_1-DisplayName"
}
}
},
{
"region": null,
"languageId": null,
"identity": {
"application": null,
"device": null,
"phone": null,
"user": {
"id": "User_2-Id",
"displayName": "User_2-DisplayName"
}
}
}
],
"mediaConfig": {
"#odata.type": "#microsoft.graph.serviceHostedMediaConfig",
"removeFromDefaultAudioGroup": null,
"preFetchMedia": []
}
}
Is any configuration missed. How to create a calling with normal message communication. Could anyone help me, thanks!
I have a breeze controller that adds an entity during the save changes that the client did not submit.
protected override bool BeforeSaveEntity(EntityInfo entityInfo)
{
if (entityInfo.Entity.GetType() == typeof(User))
{
if (entityInfo.EntityState == EntityState.Added)
{
User user = entityInfo.Entity as User;
OrganizationUser orgUser = new OrganizationUser()
{
Enabled = true,
OrganizationId = User.OrgId,
User = user
};
user.OrganizationUsers.Add(orgUser);
}
return true;
}
throw new InvalidOperationException("You can not use this service to modify an entity of type: " + entityInfo.Entity.GetType().Name);
}
When the response is returned the client side breeze manager sets the state of the server side added object as 'Added'. The OrganizationUser object above ends up with an Added state on the client. It then gets submitted in the next SaveChanges. Is this a bug?
Here is the response from the first save:
{
"$id": "1",
"$type": "Breeze.WebApi.SaveResult, Breeze.WebApi",
"Entities": [{
"$id": "2",
"$type": "LeonardoMD.Server.Api.Security.Admin.User, LeonardoMD.Server",
"Id": 9176,
"Email": "SearchProviderA#leonardoMD.com",
"FirstName": "SearchProviderA",
"LastName": "SearchProviderA",
"OrganizationUsers": [{
"$id": "3",
"$type": "LeonardoMD.Server.Api.Security.Admin.OrganizationUser, LeonardoMD.Server",
"UserId": 9176,
"User": { "$ref": "2" },
"OrganizationId": 421,
"Enabled": true
}]
}],
"KeyMappings": [{
"$id": "4",
"$type": "Breeze.WebApi.KeyMapping, Breeze.WebApi",
"EntityTypeName": "LeonardoMD.Server.Api.Security.Admin.User",
"TempValue": -1,
"RealValue": 9176
}]
}
Here is the submission of the second save:
{
"entities": [{
"Id": -2,
"CreateDate": null,
"CreateUserId": null,
"ModifyDate": null,
"ModifyUserId": null,
"Email": "SearchProviderB#leonardoMD.com",
"FirstName": "SearchProviderB",
"LastName": "SearchProviderB",
"BirthDate": null,
"GenderId": null,
"AddressLine1": null,
"AddressLine2": null,
"City": null,
"State": null,
"StateId": null,
"PostalCode": null,
"CountryId": null,
"DayPhone": null,
"DayPhoneExtension": null,
"Password": null,
"SecretQuestion": null,
"SecretAnswer": null,
"Enabled": null,
"AcceptTermsDate": null,
"entityAspect": {
"entityTypeName": "User:#LeonardoMD.Server.Api.Security.Admin",
"defaultResourceName": "Users",
"entityState": "Added",
"originalValuesMap": {},
"autoGeneratedKey": {
"propertyName": "Id",
"autoGeneratedKeyType": "Identity"
}
}
},
{
"UserId": 9176,
"OrganizationId": 421,
"Enabled": true,
"entityAspect": {
"entityTypeName": "OrganizationUser:#LeonardoMD.Server.Api.Security.Admin",
"defaultResourceName": "OrganizationUsers",
"entityState": "Added",
"originalValuesMap": {},
"autoGeneratedKey": null
}
}],
"saveOptions": {}
}
Notice the second entity is the entity returned in the response of the previous save changes. It's entityState is set to Added.
I have a work-around but its fragile and would need to be written special to every circumstance where the server returns a new entity after a save. Is there a way to set Breeze to acceptChanges on all new entities returned from the server as the the response to a saveChanges call?
manager.saveChanges()
.then(function (saveResult) {
$.each(saveResult.entities, function (i, entity) {
if (entity.organizationUsers && entity.organizationUsers().length > 0)
$.each(entity.organizationUsers(), function (index, orgUser) {
orgUser.entityAspect.acceptChanges();
});
entity.entityAspect.acceptChanges();
});
dfd.resolve();
})
.fail(function (error) { _this.handleError(context, promise, error); });
We were able to reproduce the problem and it is a bug. (The entity added on server should have returned to the client as an Unchanged entity)
We are working on a fix.
===EDIT===
The BeforeSaveEntity method is called once for each entity to be saved and should only manipulate the entity in question. You can find more about this at http://www.breezejs.com/documentation/custom-efcontextprovider.
If you want to create more entities to be saved in the server, you should do so in the BeforeSaveEntities method, where you can also add them to the saveMap dictionary to ensure they are saved in the DB.
i.e.
protected override Dictionary<Type, List<EntityInfo>> BeforeSaveEntities(Dictionary<Type, List<EntityInfo>> saveMap) {
Dictionary<Type, List<EntityInfo>> saveMapAdditions = new Dictionary<Type, List<EntityInfo>>();
var prod = this.CreateEntityInfo(product, EntityState.Added);
// add data to the entity
saveMapAdditions[typeof(Product)].Add(prod);
return base.BeforeSaveEntities(saveMap);
}
As of Breeze 1.3.5, available now, this has been fixed. and thanks for the repro...
Hi I am using swagger for documentation of my RESTful web service. wanted to know is there any way to remove the certain properties of objects from the json document response? I mean there are lots of properties that swagger gives for my method param objects and response model (e.g. notes, defaultValue, allowableValue, internalDescription etc.) that are not required for me and are null due to that the response is not much readable
For method params:
"parameters": [
{
"name": "someName1",
"description": null,
"notes": null,
"paramType": "path",
"defaultValue": null,
"allowableValues": null,
"required": true,
"allowMultiple": false,
"paramAccess": null,
"internalDescription": null,
"wrapperName": null,
"dataType": "string",
"valueTypeInternal": null
},
{
"name": "someName2",
"description": null,
"notes": null,
"paramType": "query",
"defaultValue": null,
"allowableValues": null,
"required": true,
"allowMultiple": false,
"paramAccess": null,
"internalDescription": null,
"wrapperName": null,
"dataType": "string",
"valueTypeInternal": null
}
],
-=============================================================================
For response model classes
"SomeResponseClass": {
"required": false,
"name": null,
"id": "SomeResponseClass",
"properties": {
"instanceVariable1": {
"required": false,
"name": null,
"id": null,
"properties": null,
"allowableValues": null,
"description": null,
"notes": null,
"access": null,
"default": null,
"additionalProperties": null,
"items": null,
"uniqueItems": false,
"type": "Date"
},
"instanceVariable2": {
"required": false,
"name": null,
"id": null,
"properties": null,
"allowableValues": null,
"description": null,
"notes": null,
"access": null,
"default": null,
"additionalProperties": null,
"items": null,
"uniqueItems": false,
"type": "double"
}
}
your JSON mapper is not configured to ignore null properties. You can easily address this as follows:
#Provider
#Produces(MediaType.APPLICATION_JSON)
public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
private static ObjectMapper commonMapper = null;
public JacksonJsonProvider() {
if(commonMapper == null){
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
commonMapper = mapper;
}
super.setMapper(commonMapper);
}
}
Add this mapper to your scanning properties in the web.xml and the nulls will be gone.