Using JSON.Net to parse a property of an array - json.net

I have a JSON response that I would like to parse using JSON.NET. I have done this with single values before but never when the response could contain an object that consist of an array as the errors property does below.
{
"code": "InvalidObject",
"message": "payment object is invalid",
"errors": [
{
"code": "AccountingApi",
"message": "Paid amount cannot be greater than the amount of the invoice.",
"resource": "payment",
"field": "amount"
},
{
"code": "AccountingApi",
"message": "Payment has not been verified",
"resource": "payment",
"field": "verification"
}
]
}
I would like to extract the error messages into a List. How do I specify that I want to grab the message property in the errors collection?
List<string> errorMessages = parsedJson["errors"].ToList<string>();

You could use
class Error
{
public string code { get; set; }
public string message { get; set; }
public string resource { get; set; }
public string field { get; set; }
}
class Some
{
public string code { get; set; }
public string message { get; set; }
public List<Error> errors { get; set; }
}
Then (Probably you'll send your json string as param )
List<string> parse()
{
var s = new StringBuilder();
s.Append("{");
s.Append(" \"code\": \"InvalidObject\",");
s.Append("\"message\": \"payment object is invalid\",");
s.Append("\"errors\": [");
s.Append("{");
s.Append("\"code\": \"AccountingApi\",");
s.Append("\"message\": \"Paid amount cannot be greater than the amount of the invoice.\",");
s.Append("\"resource\": \"payment\",");
s.Append("\"field\": \"amount\"");
s.Append("},");
s.Append("{");
s.Append("\"code\": \"AccountingApi\",");
s.Append("\"message\": \"Payment has not been verified\",");
s.Append("\"resource\": \"payment\",");
s.Append("\"field\": \"verification\" ");
s.Append("}");
s.Append("]");
s.Append("}");
var json = s.ToString();
var obj = JsonConvert.DeserializeObject<Some>(json);
return obj.errors.Select(x => x.message).ToList();
}

Related

Working with restricted string field values in .NET Core WebAPI 3.1

I'm working on a webapi project using .netcore.
I have a model with the following properties:
public class Criterial {
[Required]
public string Field { get; set; }
[Required]
public Operator Operator { get; set; }
[Required]
public string Value { get; set; }
public bool Result { get; set; }
}
public enum Operator {
greater_than,
equal_to,
lower_than
}
I'm trying to use enum to restrict the values that the Operator propertie can receive, but when I make a POST request to the API I got the following scenario:
POST Request Body:
"criterials": [
{
"field": "amount",
"operator": "greater_than",
"value": "50"
}
]
Response from the API:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|7e53377-444fa4a723ac655c.",
"errors": {
"$.criterials[0].operator": [
"The JSON value could not be converted to LeagueOfFateApi.Models.Operator. Path: $.criterials[0].operator | LineNumber: 5 | BytePositionInLine: 26."
]
}
}
Searching about the issue on the internet I found the [JsonConverter(typeof(JsonStringEnumConverter))] Data Annotation.
So I added it to my code and the issue was "solved":
[Required]
[JsonConverter(typeof(JsonStringEnumConverter))]
public Operator Operator { get; set; }
New response from the API:
"criterials": [
{
"field": "amount",
"operator": "greater_than",
"value": "50",
"result": false
}
]
The problem is: in my MongoDB collection a new document was saved with the int value 0 of the enums, and not the string value "greater_than":
"Criterials" : [
{
"Field" : "amount",
"Operator" : 0,
"Value" : "50",
"Result" : false
}
]
Besides, another problem is that the "criterial" field can receive any int value with no restrictions.
Is there any other practical way to restrict a string's options without using enums? Or is there anything I can add to this solution using enums?
Thank you very much for your attention and your time!
According to your description, I suggest you could write custom set and get method for the Operator property.
You could set the Operator's type is string and use Enum.IsDefined to check the Operator value is enum Operator or not.
More details, you could refer to below codes:
public class Criterial
{
[Required]
public string Field { get; set; }
private string _Operator;
[Required]
public string Operator {
get {
return this._Operator;
}
set {
if (Enum.IsDefined(typeof(Operator), value))
{
this._Operator = value;
}
else
{
this._Operator = "Error you used wrong string";
}
}
}
[Required]
public string Value { get; set; }
public bool Result { get; set; }
}
public enum Operator
{
greater_than,
equal_to,
lower_than
}
Result:

DocumentQueryException: Query expression is invalid

I need to query a collection in cosmosdb.
My entity is:
public class Tenant
{
public string Id { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string TenantDomainUrl { get; set; }
public bool Active { get; set; }
public string SiteCollectionTestUrl { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
And my controller action is:
[HttpGet]
[Route("api/Tenant/GetActiveTenant")]
public Tenant GetActiveTenant()
{
var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
return tenantStore.Query().Where(x => x.Active == true).FirstOrDefault();
}
However when trying to use this endpoint, I get this error
DocumentQueryException: Query expression is invalid, expression
https://cosmosdb-app-centralus.documents.azure.com/dbs/ToDoList/colls/tenants.Where(x
=> (x.Active == True)).FirstOrDefault() is unsupported. Supported expressions are 'Queryable.Where', 'Queryable.Select' &
'Queryable.SelectMany'
emphasized text
I am using cosmonaut nuget package.
The only document I have in the collection:
{
"ClientId": "aaaaaaaa-4817-447d-9969-e81df29c813d",
"ClientSecret": "aaaaaaaaaaaaaaaaaa/esrQib6r7FAGd0=",
"TenantDomainUrl": "abc.onmicrosoft.com",
"SiteCollectionTestUrl": "https://abc.sharepoint.com/sites/Site1",
"Active": true,
"id": "d501acc6-6b63-4f0f-9782-1473af469b56",
"_rid": "kUZJAOPekgAEAAAAAAAAAA==",
"_self": "dbs/kUZJAA==/colls/kUZJAOPekgA=/docs/kUZJAOPekgAEAAAAAAAAAA==/",
"_etag": "\"00002602-0000-0000-0000-5b69fe790000\"",
"_attachments": "attachments/",
"_ts": 1533673081
}
As Cosmonaut's ReadMe page states, you should be using the Async method extensions for Cosmonaut because they will go properly though the SDK's async flow.
For example in your case, you should change your code to await tenantStore.Query().Where(x => x.Active == true).FirstOrDefaultAsync();
PS: You should also consider adding the [JsonAttribute("id")] attribute to your Id property. Even though it's not needed, it is recommended especially if you want to do querying based on the Id.

ModelState Errormessage is Empty in Web API

Following is the Model class that I use for the application
public class APIVesselFilter
{
[Required(ErrorMessage = "Vessel is required")]
public Guid VesselID { get; set; }
public Guid? AnchorageID { get; set; }
}
Following is the Validation Filter that will check if the ModelState is Valid and if not valid I will send the error message.
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
List<string> errorList = new List<string>();
foreach (var err in actionContext.ModelState.Values)
{
foreach (var er in err.Errors)
{
errorList.Add(er.ErrorMessage);
}
}
actionContext.Response = actionContext.Request.CreateResponse(APIResponse.SendResponse(RequestStatus.GetValidationFailedMessage(), actionContext.ModelState));
}
}
}
Here, Following is the response that I get using the above Model State. Over here the error message is not in a user understandable way and so I have added the ErrorMessage in Require attribute of Vessel and I loop through the errors in ModelState. But my error message is always empty (I checked this using a debugger). What am I missing here so that the error message will be bound directly to the ModelState?
{
"Status": {
"StatusCode": 620,
"StatusMessage": "Validation Failed"
},
"Data": {
"filter": {
"_errors": [
{
"<Exception>k__BackingField": {
"ClassName": "Newtonsoft.Json.JsonSerializationException",
"Message": "Required property 'VesselID' not found in JSON. Path '', line 1, position 56.",
"Data": null,
"InnerException": null,
"HelpURL": null,
"StackTraceString": " at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EndObject(Object newObject, JsonReader reader, JsonObjectContract contract, Int32 initialDepth, Dictionary`2 propertiesPresence)",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": "8\nEndObject\nNewtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed\nNewtonsoft.Json.Serialization.JsonSerializerInternalReader\nVoid EndObject(System.Object, Newtonsoft.Json.JsonReader, Newtonsoft.Json.Serialization.JsonObjectContract, Int32, System.Collections.Generic.Dictionary`2[Newtonsoft.Json.Serialization.JsonProperty,Newtonsoft.Json.Serialization.JsonSerializerInternalReader+PropertyPresence])",
"HResult": -2146233088,
"Source": "Newtonsoft.Json",
"WatsonBuckets": null
},
"<ErrorMessage>k__BackingField": ""
}
],
"<Value>k__BackingField": null
}
}
}
Try decorating your model property with a DisplayAttribute:
public class APIVesselFilter
{
[Required]
[Display(Name="Vessel is required")]
public Guid VesselID { get; set; }
public Guid? AnchorageID { get; set; }
}
I know this is the way to customise your messages when using the Html.ValidationSummary and a quick test showed this comes up when inspecting the ModelState in an action.
using CreateErrorResponse instead of CreateResponse might solve your problem.
I faced a smiliar problem and was fixed with that.
In your case this will be
actionContext.Response = actionContext.Request.CreateErrorResponse(APIResponse.SendResponse(RequestStatus.GetValidationFailedMessage(), actionContext.ModelState));

Asp.Net Wep Api 2 Error When Posting Json Object

I'm developing 3 simple RESTFul services by using ASP.NET Web API 2 and EF6
The name of first service is ImageGallery, which returns ImageGallery json object from Database
I have two entities like these:
ImageGalley.cs:
public class ImageGallery
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Image> Images { get; set; }
}
And Also, Image.cs:
public class Image
{
[Key]
public int ID { get; set; }
public int ImageGalleryID { get; set; }
public string Caption { get; set; }
public string Url { get; set; }
public virtual ImageGallery ImageGallery { get; set; }
}
My Controller's Get method:
public IList<ImageGallery> GetImageGalleries()
{
var imgGalls = db.ImageGalleries.ToList();
return imgGalls;
}
For Post:
[ResponseType(typeof(ImageGallery))]
public IHttpActionResult PostImageGallery(ImageGallery imageGallery)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.ImageGalleries.Add(imageGallery);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = imageGallery.ID }, imageGallery);
}
I have put this line of code in my Global.asax to avoid self referencing loop:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
I'm using POSTMAN to get and post Json Objects. But when i'm trying the Post, i encounter that error.
{
"Message": "The request is invalid.",
"ModelState": {
"imageGallery": [
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MobileApis.Models.ImageGallery' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath '', line 1, position 1."
]
}
}
Here is my GET Response:
[
{
"Images": [
{
"ID": 3,
"ImageGalleryID": 1,
"Caption": "Image 1",
"Url": "http://placehold.it/350x150"
},
{
"ID": 4,
"ImageGalleryID": 1,
"Caption": "Image 2",
"Url": "http://placehold.it/350x150"
},
{
"ID": 5,
"ImageGalleryID": 1,
"Caption": "Image 3",
"Url": "http://placehold.it/350x150"
},
{
"ID": 6,
"ImageGalleryID": 1,
"Caption": "Image 4",
"Url": "http://placehold.it/350x150"
}
],
"ID": 1,
"Name": "Image Gallery 1"
}
]
I will be so happy, if you help me.

Parsing device listing from Urban Airship with JSON.Net

For the life of me, I can't figure out how to parse the collection of device_tokens out of this using JSON.Net. I can parse out the top level collection fine, but am bombing on parsing out the device tokens in any way shape or form. Anyone have any ideas?
{
"next_page": "https://go.urbanairship.com/api/device_tokens/?start=<MY_TOKEN>&limit=2",
"device_tokens_count": 87,
"device_tokens": [
{
"device_token": "<MY_TOKEN>",
"active": false,
"alias": null,
"tags": []
},
{
"device_token": "<MY_TOKEN>",
"active": true,
"alias": null,
"tags": ["tag1", "tag2"]
}
],
"active_device_tokens_count": 37
}
Heres how you can do it using Json.NET
First create a class to represent a single device_token:
public class DeviceToken
{
public string device_token { get; set; }
public bool active { get; set; }
public object alias { get; set; }
public List<object> tags { get; set; }
}
Then using the JsonConvert class you can deserialize the json device_token array to a list of DeviceToken objects.
string json = "{\"next_page\": \"https://go.urbanairship.com/api/device_tokens/?start=07AAFE44CD82C2F4E3FBAB8962A95B95F90A54857FB8532A155DE3510B481C13&limit=2\",\"device_tokens_count\": 87,\"device_tokens\": [{\"device_token\": \"0101F9929660BAD9FFF31A0B5FA32620FA988507DFFA52BD6C1C1F4783EDA2DB\",\"active\": false,\"alias\": null,\"tags\": []},{\"device_token\": \"07AAFE44CD82C2F4E3FBAB8962A95B95F90A54857FB8532A155DE3510B481C13\",\"active\": true,\"alias\": null,\"tags\": [\"tag1\", \"tag2\"] }],\"active_device_tokens_count\": 37}";
JObject obj = JObject.Parse(json);
var deviceTokens = JsonConvert.DeserializeObject<List<DeviceToken>>(obj["device_tokens"].ToString());

Resources