Deserialize json to a customize object with json.net - c#

I'm trying to deserialize json-formatted response below.
{
"context": "xxxxxx"
"value": [
{
"Id": "123"
"Time": "2022-12-01"
}
{
"Id": "123"
"Time": "2022-12-01"
}
....
]
}
According to this: https://www.newtonsoft.com/json/help/html/deserializeobject.htm, this code should work.
public class WorkingSetContent
{
/// <summary>Collection ID</summary>
[JsonProperty("context")]
public string Context { get; set; }
/// <summary>UserRelationship</summary>
[JsonProperty("value")]
public IList<ItemClass> Items { get; set; }
}
But I'm getting a build error : "Change 'Items' to be read-only by removing the property setter."
I changed the setter to private to avoid this build error, then I was able to run it, but it causes a runtime error as null value is passed.

This is the code analysis rule you're running up against.
One option is to initialize your collection property with an empty list:
[JsonProperty("value")]
public IList<ItemClass> Items { get; } = new List<ItemClass>();
However, the code analysis rule explicitly says:
You can suppress the warning if the property is part of a Data Transfer Object (DTO) class.
Since you're deserializing this class from JSON, I think it's safe to assume it's a DTO. I would recommend using a pattern in your .globalconfig or .editorconfig files to suppress this rule for all of your DTO model classes.

You have to fix your json
{
"context": "xxxxxx",
"value": [
{
"Id": "123",
"Time": "2022-12-01"
},
{
"Id": "123",
"Time": "2022-12-01"
}
]
}

Related

Strongly Typed IDs and JSON Schema generation in C#

I like the idea of Strongly Typed IDs and I am using it for some time. I use it also in DTOs without and major problems... till now. I have a use case where I need to generate JSON Schema from some classes which uses Strongly Type IDs like following:
[StronglyTypedId(StronglyTypedIdBackingType.Long)]
public partial struct TweetId
{
}
public class Tweet
{
public TweetId Id {get; set;}
}
So, as described, TweetID is represented as long base type.
The problem arises when I want to generate JSON Schema from this type. I am currently using Newtonsoft.Json.Schema (I also tried some others) using this code:
JSchemaGenerator generator = new JSchemaGenerator();
JSchema quotesSchema = generator.Generate(typeof(Tweet));
The result I get is:
{
"definitions": {
"Tweet": {
"type": [
"object"
],
"properties": {
"Id": {
"$ref": "#/definitions/TweetId"
}
}
},
"TweetId": {},
},
"type": "object",
"$ref": "#/definitions/Tweet"
}
But what I want is:
{
"definitions": {
"Tweet": {
"type": [
"object"
],
"properties": {
"Id": {
"type": "integer"
}
}
}
},
"type": "object",
"$ref": "#/definitions/Tweet"
}
Do you have any idea how to achive this? Newtonsoft.Json.Schema is not mendatory.

Deserializes JSON to an object in c# using json.net

I am trying to convert my json into a rule object. I have been following this guide from Newtonsoft http://www.newtonsoft.com/json/help/html/deserializeobject.htm.
public class Rule{
public string Field { get; set; }
public string Test { get; set; }
public Rule[] Cases { get; set; }
}
public class Rules {
public List<Rule> Root{ get; set; }
}
My Json from rules.js
{
"Rules": [{
"Field": "Subject",
"Test": "^(Azure Exception)",
"Cases": [{
"Field": "Content",
"Test": "Hostname: az.....(?<Hostname>[^\n])",
"Cases": [{
"Field": "Content",
"Test": "Hostname:\\s+(?<Hostname>.*)\\s+Site name:\\s+(?<SiteName>.*)"
}]
}]
}]
}
In my main method:
String RulesFile = "cSharp/rules.js";
String Json = System.IO.File.ReadAllText(RulesFile);
Rule rule = JsonConvert.DeserializeObject<Rule>(Json);
var rules = JsonConvert.DeserializeObject<Rules>(Json);
//rule.Cases
//rule.Field
//rule.Test
//rules.Root
Console.Write(rule.Field);
I've tested my json and i can output it in my terminal. I'm unsure how to assign each field in json to my rules objects. Looking at the newtonsoft docs this should work, but I'm not getting any output.
I want to be able to print these fields out, anyone know to do it?
Cheers all in advance.
In your JSON string, the root object is an object with a Rules property. That property is an array of objects. You need to define and deserialize the root object, eg
class Rules
{
public Rule[] Rules{get;set;}
}
var rules = JsonConvert.DeserializeObject<Rules>(Json);
You can generate the DTOs requires for deserialization in Visual Studio by copying the JSON string and select Paste JSON as Classes in the Edit menu. You can also generate classes by using an online converter like json2csharp

In C#, how can i deserialize this json?

I am getting this JSON data back from a REST service that looks like this:
[ [ [ {"Name": "Joe", "Comment": "Load", "Updated": null, "Test": ""} ] ] ]
or
[ [ [ {"Name": "Joe", "Comment": "Load", "Updated": null, "Test": ""}, {"Name": "Bill", "Comment": "123", "Updated": null, "Test": ""} ] ] ]
I did a "Copy JSON as classes" feature in visual studio and it created this:
public class Rootobject
{
public Project[][][] Property1 { get; set; }
}
public class Project
{
public string Name { get; set; }
public string Comment { get; set; }
public string Updated { get; set; }
public string Test { get; set; }
}
but when i try to deserialize using this code:
var results = new JsonDeserializer().Deserialize<Rootobject>(response);
I get an error stating:
An exception of type 'System.InvalidCastException' occurred in RestSharp.dll but was not handled in user code
Additional information: Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'
Could you please advise on what I might be doing wrong (NOTE: i don't have any control over how the data comes in so changing the format isn't an option)
Also, to confirm this seems to be valid JSON from JSONLlint:
Using Newtonsoft.Json nuget package,
try
JSONConvert.DeserialiseObject<Rootobject>(response)
EDIT: BTW, I tried to use your json on http://json2csharp.com/ and it says Parsing your JSON didn't work. Please make sure it's valid. So I doubt that any json parsing library will be able to parse your JSON.
However implementing your own deserializer is possible and an ideal solution when external services return invalid JSON
I can probably help you deserialize it if you show me what JSON you get when service returns multiple Project objects.
EDIT2: Szabolcs's solutions seems promising, but I would still suggest testing it with JSON for multiple Product objects. I smell something bad & its the shitty third party service. Always good to test.
You can deserialize that particular JSON like this using Json.NET:
var json = "[ [ [ {\"Name\": \"Joe\", \"Comment\": \"Load\", \"Updated\": null, \"Test\": \"\"}, "+
" {\"Name\": \"Bill\", \"Comment\": \"123\", \"Updated\": null, \"Test\": \"\"} ] ] ]";
var deserializedObject = JsonConvert.DeserializeObject<List<List<List<Project>>>>(json);
And to get all the Projects from the nested lists:
var allProjects = deserializedObject.SelectMany(x => x.SelectMany(y => y)).ToList();

retrieve item from a json file c#

{
"_id": "underscore",
"_rev": "136-824a0ef7436f808755f0712c3acc825f",
"name": "underscore",
"description": "JavaScript's functional programming helper library.",
"dist-tags": {},
"versions": {
"1.0.3": {
"name": "xxx",
"description": "xxx"
},
"1.0.4": {},
"1.1.0": {}
}
}
I would like to retrieve the latest version(1.1.0) from the json file. However, it always gives out me errors of "can not deserialize json object into type RootObject
Here is my class
public class versions
{
public string name { get; set; }
public string description { get; set; }
}
public class RootObject
{
public List<versions> vs { get; set; }
}
And here is where I used it
RootObject[] dataset = JsonConvert.DeserializeObject<RootObject[]>(json);
Any idea. Many thankx
Update:
I have updated the JSON file format, but some problem..
I think the problem is, that in JSON you have to quote all "field"/attribute names. (Thats a difference from standard Javascript-Notation, where you can have unquoted attributes).
So, your file should be like:
{
"_id" : "underscore",
"versions": {
"1.0.3" : {
"name": "xxx",
"description": "xxx"
}
}
Note that {1.0.3: { name: "xxx" } } wouldn't be valid JavaScript either since '1.0.3' is an invalid identifier in JavaScript.
Looking at the JSON in your updated answer:
{
"_id" : "underscore",
"versions": {
"1.0.3" : {
"name": "xxx",
"description": "xxx"
},
"1.0.4" : {
"name": "xxx",
"description": "xxx"
}
}
This is still Invalid JSON - you have 4 opening { and only 3 closing }
you should use http://jsonlint.com/ - to validate your JSON and ensure it is Valid
I've fixed your json in question. Now for your real question
I would like to retrieve the latest version(1.1.0) from the json file. However, it always gives out me errors of "can not deserialize json object into type RootObject
You have property names like 1.0.3 that are unknown at compile time. So you can not deserialize them to a concrete class. You should handle them dynamically.
Try this:
var versions = JObject.Parse(json)["versions"]
.Children()
.Cast<JProperty>()
.ToDictionary(c => c.Name, c => c.Value.ToObject<versions>());

Deserialize nested & unstructured BsonDocument (mongodb c# driver)

Let's say this is a collection of 2 Bson documents
{
"_id": "...",
"name": "Test1",
"sub": {
"street": "134 Fake Street",
"city": "NoWhere"
}
},
{
"_id": "...",
"name": "Test2",
"sub": {
"height": "10",
"width": "20",
"sub2": {
"type": "something"
}
}
}
where the first level is a structured class but sub-levels can be completely unstructured and can have further nested documents several levels deep.
How can I deserialize this document to a C# class? All samples I have seen assume some structure in nested documents.
The following class gives an error:
public class Report
{
[BsonId]
public ObjectId _id { get; set; }
public string name { get; set; }
public BsonDocument sub { get; set; }
}
Type 'MongoDB.Bson.BsonString' with data contract name '...' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
EDIT
What I'm trying to do might be complete non-sense. Is it a better idea to just use one BsonDocument and handle everything manually without a structured class?
I don't think the error message you are getting is from the C# driver. Can you please provide a stack trace?
I've tried to reproduce your issue but it works fine with my test program. See:
http://pastie.org/5032283
The document inserted by the above test program looks like this:
> db.test.find()
{ "_id" : ObjectId("5075fc6ee447ad1354c1f018"), "name" : "John Doe", "sub" : { "x" : 1, "y" : 2 } }
>

Categories