frenk91
frenk91

Reputation: 929

Deserializing Json Schema to Json String or Object

I have a json schema and I need to convert it to a C# object or at least into json string.

is there any way to do it by code or by using some tool?

for the Json I'm currently using Json.net.

this is one of my schema:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "UserGroupWsDTO",
  "type": "object",
  "properties":
  {
    "members":
    {
      "type": "array",
      "items":
      {
        "type": "object",
        "properties":
        {
          "uid":
          {
            "type": "string"
          }
        }
      }
    },
    "uid":
    {
      "type": "string"
    },
    "name":
    {
      "type": "string"
    }
  }
}

I need this to create an Object for deserialize the json

EDIT My Json schema version is 4 and JSON Schema to POCO doesn't support it

Upvotes: 1

Views: 3403

Answers (2)

eoinmullan
eoinmullan

Reputation: 1199

Have a look at JSON Schema to POCO which supports v3 JSON.

Upvotes: 1

If you are just "browsing" key-values, then you don't need any extra libs...

just do:

var obj = (JObject)JsonConvert.DeserializeObject(json);

var dict = obj.First.First.Children().Cast<JProperty>()
            .ToDictionary(p => p.Name, p =>p.Value);

var dt =  (string)dict["title"];

but if instead you need an object of the string, then define a class and deserialize the string to that class... follow this example:

1st define the classes:

public class Uid
{
    public string type { get; set; }
}

public class Properties2
{
    public Uid uid { get; set; }
}

public class Items
{
    public string type { get; set; }
    public Properties2 properties { get; set; }
}

public class Members
{
    public string type { get; set; }
    public Items items { get; set; }
}

public class Uid2
{
    public string type { get; set; }
}

public class Name
{
    public string type { get; set; }
}

public class Properties
{
    public Members members { get; set; }
    public Uid2 uid { get; set; }
    public Name name { get; set; }
}

public class RootObject
{
    public string __invalid_name__$schema { get; set; }
    public string title { get; set; }
    public string type { get; set; }
    public Properties properties { get; set; }
}

and this is the implementation:

 string json = @"{...use your json string here   }";

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

    Console.WriteLine(root.title);
    // UserGroupWsDTO

Upvotes: 0

Related Questions