简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM