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());
Related
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:
I have an issue where an array object in my config.json is coming back as empty. In the following code, gridFields will come back as empty.
{"grids": [{
"name": "Grid1"
"gridFields": [
{
"Name": "Something",
"Label": "Something"
},
{
"Name": "SomethingElse",
"Label": "SomethingElse"
}]
},
{"name": "Grid2"
"gridFields": [
{
"Name": "Something",
"Label": "Something"
}]
}]
}
I have matching POCOs and made sure the names match up as follows.
public class Grid
{
public string name { get; set; }
public gridFields gridFields {get; set;}
}
public class gridFields
{
public List<gridField> GridFields { get; set; } = new List<gridField>();
public int Count => GridFields.Count();
public IEnumerator GetEnumerator()
{
return GridFields.GetEnumerator();
}
}
public class gridField
{
public string Name { get; set; }
public string Label { get; set; }
}
In my startup I have the following
public void ConfigureServices(IServiceCollection services)
{ services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
var config = new List<Grid>();
Configuration.Bind("grids", config);
services.AddSingleton(config);
}
The config.gridFields ends up holding no values. I have values for name, but not gridFields. Even if I make gridFields List it comes back null.
My question is if there is someway following this current code that I can get the data out of this array in array, or do I need to do something completely different. Why isn't .net core able to bind every object it comes across underneath the parent?
The example json misses a , after the name of each grid.
{
"name": "Grid2",
"gridFields":
[{
"Name": "Something",
"Label": "Something"
}]
}
You have a list of gridField directly under the Grid in the Json.
In the Code however you use another object, GridFields.
You should remove the gridfiels class and use a list of gridField in the Grid class:
public class Grid
{
public string name { get; set; }
public List<gridField> gridFields {get; set;}
}
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.
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();
}
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.