Givi Bibileishvili
Givi Bibileishvili

Reputation: 63

Create Object from dictionary with Json

How to serialize Dictionary to json object

 var dict = new Dictionary<string, string>()
        {
            {"Username", "{Username}"},
            {"FirstName", "{FirstName}"},
            {"LastName", "{LastName}"},
            {"AccountMeta[0].MetaKey", "Pincode"},
            {"AccountMeta[0].MetaValue", "150000"},

        };
public class Account {
    public string Username {get;set;}
    public string FirstName{get;set;}
    public string LastName {get;set;}
    public List<AccountMeta> AccountMeta {get;set;}
}

And Objects:

public class AccountMeta{
     public string MetaKey {get;set;}
     public string MetaValue{get;set;}
 }

Upvotes: 0

Views: 708

Answers (1)

Rafael
Rafael

Reputation: 2753

Use the library Newtonsoft.Json here

Manages serialization of any kind of objects gracefully and its free.

The Json format provides an standard way to serialize arrays and neasted objects, and it doesn't support for object paths. So your aproach for serializing Lists as "List[index]" = "value" and object properties as "Object.Property" = "Value" style would not work

Install the package: Newtonsoft.Json Example of use:

Dictionary<string, string> dictionary = ...;
string Json = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary);

MyClass Result = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass >();

Upvotes: 3

Related Questions