将键值对的数组转换为Json字符串

时间:2013-12-12 11:37:02

标签: c# json

我有来自Service的对象数组

[0]= {
        Name=Only for Testing 
        soldTo=0039000000
        city=Testing
        State=IN
        address1=Testing
        address2=
        zip=5600
        country=US
     }

所以可能会这样。我需要将此返回给Js,以便我可以解析并将值绑定到UI控件

如何将此数组转换为Json字符串?

1 个答案:

答案 0 :(得分:1)

因为你有一个表示从服务返回的数据的类,如果你不介意将整个类属性返回给你的客户端,那么只需使用其中一个json序列化器。从这里开始:http://www.nuget.org/packages?q=json

如果要减少序列化的字段数,请创建自己的类,将服务对象转换为自己的类,然后使用相同的技术对其进行序列化。

以下是显示如何序列化的Json.Net文档。 http://james.newtonking.com/json/help/index.html

更新:显示转换和序列化

注意:使用ServiceStack序列化程序https://github.com/ServiceStack/ServiceStack.Text

// get data from the service
var serviceData = new List<ServiceObject>
{
    new ServiceObject { name = "one", soldTo = "00000123", city = "sydney", state = "nsw", addressLine1 = "king st", addressLine2 = "", zip = "0123", country = "australia" },
    new ServiceObject { name = "two", soldTo = "00000456", city = "melbourne", state = "vic", addressLine1 = "william st", addressLine2 = "", zip = "0456", country = "australia" },
    new ServiceObject { name = "three", soldTo = "00000789", city = "adelaide", state = "sa", addressLine1 = "county cres", addressLine2 = "", zip = "0789", country = "australia" }
};

// convert it to what you want to return
var jsData = (from row in serviceData
              select new JsObject
              {
                  name = row.name,
                  soldTo = row.soldTo,
                  address = new JsAddress
                  {
                      line1 = row.addressLine1,
                      line2 = row.addressLine2,
                      postCode = row.zip,
                      state = row.state,
                      country = row.country
                  }
              }).ToList();

// turn it into a json string
var json = JsonSerializer.SerializeToString(jsData);

// this will spit out the result when using Linqpad
json.Dump("json");

}

class ServiceObject
{
    public string name { get; set; }
    public string soldTo { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string addressLine1 { get; set; }
    public string addressLine2 { get; set; }
    public string zip { get; set; }
    public string country { get; set; }
}

class JsObject
{
    public string name { get; set; }
    public string soldTo { get; set; }
    public JsAddress address { get; set; }
}

class JsAddress
{
    public string line1 { get; set; }
    public string line2 { get; set; }
    public string state { get; set; }
    public string postCode { get; set; }
    public string country { get; set; }

干杯,亚伦