0

I have to serialize into json some informations and then write them to a file. Actually the result i want to achieve is this:

{
  "Email": "[email protected]",
  "Active": true,
  "CreatedDate": "2013-01-20T00:00:00Z",
  "libraries": [
    {
      "name": "name1"
    },
    {
      "name": "name2"
    }
  ]
}

this is the class i use to store info:

public class JSON
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public string[] libraries { get; set; }
}

and then i use this to serialize them:

JSON account = new JSON
{
    Email = "[email protected]",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    libraries = new[] {"Small","Medium","Large" }

};

string json = JsonConvert.SerializeObject(account, Formatting.Indented);

the problem is that actually the result i have is this:

{
  "Email": "[email protected]",
  "Active": true,
  "CreatedDate": "2013-01-20T00:00:00Z",
  "libraries": [
    "Small",
    "Medium",
    "Large"
  ]
}

how can i solve it?

3 Answers 3

5

Change your JSON class to this one:

public class Library
{
    public string name { get; set; }
}

public class JSON
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public string CreatedDate { get; set; }
    public List<Library> libraries { get; set; }
}

How to generate classes with online tool

The good hint is to use JSON to C# converter which will generate you C# classes.

How to generate classes with Visual Studio

Other option is to use built in Visual Studio feature (works in VS2013 and above).

If you have your JSON file in the clipboard you can go:

Edit->Paste Special->Paste JSON as Classes

How to use new class

JSON account = new JSON
{
    Email = "[email protected]",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    libraries = new List<Library>  
            {
              new Library {name = "Small"},
              new Library {name = "Medium"},
              new Library {name = "Large"} 
            }

};
Sign up to request clarification or add additional context in comments.

3 Comments

and what do i do with this? libraries = new[] {"Small","Medium","Large" }
it works fine if i use public Library[] libraries { get; set; } instead of public List<Library> libraries { get; set; }. With that it give me a conversion error
Yep, you're right. I updated the example one more time. You either use array or a List.
0

You can use custom converter:

public class ArrayItemAsObjectConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string[]);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        string[] items = (string[])value;

        writer.WriteStartArray();

        for (int i = 0; i < items.Length; i++)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("name");
            writer.WriteValue(items[i]);
            writer.WriteEndObject();
        }

        writer.WriteEndArray();
    }
}
///

[JsonConverter(typeof(ArrayItemAsObjectConverter))]
public string[] libraries { get; set; }

Comments

0

Using Visual Studio, you can create the classes:

public class Rootobject
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public Library[] libraries { get; set; }
}

  public class Library
  {
      public string name { get; set; }
  }

You need copy the json string and paste special as json class. Go to the menu then click EDIT and you will find it.

And

using System.Web.Script.Serialization;

JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.