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

本文关键字:Json 字符串 转换 键值对 数组 | 更新日期: 2024-09-20 11:54:11

我有一个来自Service的对象数组,类似于这个

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

所以可能喜欢这样。我需要将其返回给Js,这样我就可以解析并将值绑定到UI控件

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

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

因为您有一个表示从服务返回的数据的类,如果您不介意将整个类属性返回到客户端,那么只需使用众多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; }

干杯,Aaron