Siva Rajagopal
Siva Rajagopal

Reputation: 71

Object to json convertion format using serializer

I have the following c# model object

public class AddressUserFields
{
    public string number { get; set; }
    public string street { get; set; }
    public string apartment { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string zipcode { get; set; }
    public string DPV { get; set; }
}

When I am trying to convert it to json string using json serialization method, it will convert like the following,

JSON string: {userFields:[{"number":null,"street":null,"apartment":"","city":null,"state":null,"zipcode":null,"DPV":null}]}

But actually I look for like the below, Expected JSON result:

{userFields:[{"number":null},{"street":null},{"apartment":""},{"city":null},{"state":null},{"zipcode":null},{"DPV":null}]}

So could any one give the way to design my c# model object and get the expected json result.

Upvotes: 0

Views: 39

Answers (1)

MichaC
MichaC

Reputation: 13390

You just have to create your poco objects in the structure your want the Json to be in.

If you want this structure:

{userFields:
  [
   { "number":null,
     "street":null,
     "apartment":"",
     "city":null,
     "state":nul‌​l,
     "zipcode":null,
     "DPV":null
   }
  ]
 }

This is an object with one property userFields of type AddressUserFields[].

So just add another class

public class SomeContainer
{
     public AddressUserFields[] userFields {get;set;}
}

and serialize that one

If you really want an array of different objects which all have different properties, like what you posted:

...[{"number":null},{"street":null},{"apartment":""},...]

you can use an array of Dictionary<TKey,TValue>, like this:

public class Fields
{
    public Dictionary<string, string>[] userFields { get; set; }
}

and use it like so?

var fields = new Fields()
{
    userFields = new[]{
        new Dictionary<string,string>(){{"number", null}},
        new Dictionary<string,string>(){{"street", null}}
    }
};

var json = JsonConvert.SerializeObject(fields);

Upvotes: 2

Related Questions