How to Auto-Generate a C# Class File from a Json String

How to auto-generate a C# class file from a JSON string

Five options:

  • Use the free jsonutils web tool without installing anything.

  • If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.

  • Use the free jsonclassgenerator.exe

  • The web tool app.quicktype.io does not require installing anything.

  • The web tool json2csharp also does not require installing anything.

Pros and Cons:

  • jsonclassgenerator converts to PascalCase but the others do not.

  • app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.

How below JSON can be converted into C# classes?

Try this structure:

public partial class MainObjClass
{
[JsonProperty("objects")]
public Objects Objects { get; set; }
}

public partial class Objects
{
[JsonProperty("gujarat")]
public Gujarat Gujarat { get; set; }
}

public partial class Gujarat
{
[JsonProperty("type")]
public string Type { get; set; }

[JsonProperty("geometries")]
public Geometry[] Geometries { get; set; }
}

public partial class Geometry
{
[JsonProperty("arcs")]
public Arc[][] Arcs { get; set; }

[JsonProperty("type")]
public string Type { get; set; }

[JsonProperty("properties")]
public Properties Properties { get; set; }
}

public partial class Properties
{
[JsonProperty("dt_code")]
[JsonConverter(typeof(ParseStringConverter))]
public long DtCode { get; set; }

[JsonProperty("year")]
public string Year { get; set; }
}

public partial struct Arc
{
public long? Integer;
public long[] IntegerArray;

public static implicit operator Arc(long Integer) => new Arc { Integer = Integer };
public static implicit operator Arc(long[] IntegerArray) => new Arc { IntegerArray = IntegerArray };
}

You have to break down each key element from JSON to a C# class/structure. Then nest objects and parse.

JSON converting into C# or classes

Based on your comments (hopefully, I understand it)...

{
"unknown_a" : {...},
"unknown_b" : {...},
"unknown_c" : {...},
"unknown_d" : {...},
"foo" : true, // known property
"bar" : { // known property
"x" : "xxx",
"y" : "yyy"
}
}

I'm thinking that you want a Dictionary<string, object>?

Then you can do a little bit of your own conversion magic --- for example (just to get the concept out there)

foreach (d in dictionary)
{
switch (d.Key)
{
case "foo": ... // known property
obj.Foo = (bool)d.Value;
break;
case "bar": ... // known property
obj.Bar = (Bar)d.Value;
break;
default: ... // according to your comments, these are known types
try
{
obj.Files.Add((File)d.Value);
}
catch {...}
break;
}
}

How to parse/map a JSON in C# and locate specific classes to output

Firstly, you need to create model class which represents properties of the json object.
For example based on your json file, you can create the following class:

public class RootItem // or whatever name of the root object
{
[JsonPropertyName("_id")]
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }

[JsonPropertyName("download")]
public IEnumerable<Download> Downloads { get; set; }
}

public class Download
{
public string Sha1 { get; set; }
public string Url { get; set; }
}

Secondly, you need to deserialize object (extracting data from a json file). You can use built-in json serializer from System.Text.Json, or you can use Newtonsoft.Json if you are using old frameworks.

In the following example I used default System.Text.Json serializer:

var jsonData = File.ReadAllText("here path of the json file");
var serializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var rootObj = JsonSerializer.Deserialize<RootItem>(jsonData, serializerOptions);

Then get whatever data from deserialized object (in our case it's rootObj)
If you want to print all urls then you can do something like:

foreach(var download in rootObj.Downloads)
{
Console.WriteLine(download.Url)
}

How to parse complex json to c# .net classes

The initial property is almost certainly meant to be a dictionary key, so I would go with something like this:

public class Language
{
[JsonProperty("lanCODE")]
public string LanguageCode { get; set; }

public string Default { get; set; }

public List<string> SystemLocale { get; set; }

public GenNames GenNames { get; set; }
}

public class GenNames
{
public List<string> Female { get; set; }
public List<string> Male { get; set; }
}

And deserialise like this:

var languages = JsonConvert.DeserializeObject<Dictionary<string, Language>>(json);

How to auto-generate a C# class file from a JSON string

Five options:

  • Use the free jsonutils web tool without installing anything.

  • If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.

  • Use the free jsonclassgenerator.exe

  • The web tool app.quicktype.io does not require installing anything.

  • The web tool json2csharp also does not require installing anything.

Pros and Cons:

  • jsonclassgenerator converts to PascalCase but the others do not.

  • app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.

deserializing dynamic named JSON attributes to a C# class

Based on your JSON, the class structure you need is this:

public class RootObject
{
public Dictionary<Guid, Document> Documents { get; set; }
}

public class Document
{
public Guid Id { get; set; }
public string Name { get; set; }
public Dictionary<Guid, Sys> Sys { get; set; }
}

public class Sys
{
public Guid Id { get; set; }
public string Name { get; set; }
}

Then deserialize into the RootObject class like this:

var root = JsonConvert.DeserializeObject<RootObject>(json);

Here is a working demo: https://dotnetfiddle.net/Uycomw



Related Topics



Leave a reply



Submit