如何将此C#对象序列化为JSON?

时间:2017-05-16 13:43:40

标签: c# json serialization

这是我追求的输出:

  "key": "rbp_role_config",
  "value": {
    "customer_group_1": {
      "group_price": {
        "price": "150",
        "price_type": "currency"
      }
    },
    "customer_group_2": {
      "group_price": {
        "price": "125",
        "price_type": "currency"
      }
    }
  }

以下是我的课程:

[DataContract]
public class ProductMeta
{
    /// <summary>
    /// Meta ID. 
    /// read-only
    /// </summary>
    [DataMember(EmitDefaultValue = false)]
    public int? id { get; set; }

    /// <summary>
    /// Meta key.
    /// </summary>
    [DataMember(EmitDefaultValue = false)]
    public string key { get; set; }

    /// <summary>
    /// Meta value.
    /// </summary>
    [DataMember(EmitDefaultValue = false)]
    public object value { get; set; }
}

[DataContract]
public class ProductPriceGroup
{

    /// <summary>
    /// Meta Value
    /// </summary>
    [DataMember(EmitDefaultValue = false)]
    public ProductGroupPrice group_price { get; set; }
}

[DataContract]
public class ProductGroupPrice
{
    /// <summary>
    /// Product Price
    /// </summary>
    [DataMember(EmitDefaultValue = false)]
    public string price { get; set; }

    /// <summary>
    /// Product Price Type
    /// </summary>
    [DataMember(EmitDefaultValue = false)]
    public string price_type { get; set; }
}

将从SQL表中获取值&#34; customer_group_1&#34;,&#34; customer_group_2&#34;等,因此它们必须是动态属性。

最后这里是使用类的代码:

using (var connection = new SqlConnection(_connectionString))
using (var command = new SqlCommand(queryString, connection))
{
    try
    {
        connection.Open();
    }
    catch (SqlException sqlEx)
    {
        log.Error(sqlEx.Message);
        return null;
    }

    var reader = command.ExecuteReader();
    var productMetaDict = new Dictionary<string, ProductPriceGroup>();

    while (reader.Read())
    {
        try
        {
            var group = StringToSlug(reader["customerpricegroup"].ToString());
            productMetaDict.Add(group, new ProductPriceGroup() { group_price = new ProductGroupPrice { price = reader["regular_price"].ToString(), price_type = "currency" } });

        }
        catch (SqlException sqlEx)
        {
            log.Error(sqlEx.Message);
        }
   }

   if (productMetaDict.Count > 0)
   {
       var productMeta = new ProductMeta();
       productMeta.key = "rbp_role_config";
       productMeta.value = productMetaDict;
       return productMeta;
   };

我在EBrown的帮助下重写了我的代码,现在我正在返回我想要的JSON,但出于某种原因,我在尝试将其添加到元数据属性时获得了First Chance Exceptions该产品。

为了便于说明,在转换为字符串时,我得到以下内容:

"key": "rbp_role_config",
"value": {
    "customer_group_1": {
        "group_price": {
            "price": "100,70",
            "price_type": "currency"
        }
    },
    "customer_group_2": {
        "group_price": {
            "price": "100,70",
            "price_type": "currency"
        }
    }
}

我有一个具有以下属性的Product类:

/// <summary>
/// Meta data. See Product - Meta data properties
/// </summary>
[DataMember(EmitDefaultValue = false)]
public List<ProductMeta> meta_data { get; set; }

当尝试将元数据对象添加到此列表时,我得到&#34;类型&#39; System.NullReferenceException&#39;的第一次机会异常。发生&#34 ;. &#34; P&#34;这是一个Product对象。我已经检查过,p不为空,productMeta不为空。

p.meta_data.Add(productMeta);
编辑:我很傻,忘了为meta_data属性创建一个List ......

p.meta_data = new List<ProductMeta>();

现在我没有获得任何第一次机会例外。

全部完成!谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

看起来并不困难,只需生成与JSON相同结构的POCO(或其中一组):

public class Root
{
    public ProductMeta[] meta_data { get; set; }
}

public class ProductMeta
{
    public int? id { get; set; }
    public string key { get; set; }
    public Dictionary<string, ProductPriceGroup> value { get; set; }
}

public class ProductPriceGroup
{
    public ProductGroupPrice group_price { get; set; }
}

public class ProductGroupPrice
{
    public string price { get; set; }
    public object price_type { get; set; }
}

这是我的代码:

var serObj = new Root();
serObj.meta_data = new ProductMeta[1];
serObj.meta_data[0] = new ProductMeta();
serObj.meta_data[0].id = 220910;
serObj.meta_data[0].key = "rbp_role_config";
serObj.meta_data[0].value = new Dictionary<string, ProductPriceGroup>();
serObj.meta_data[0].value.Add("customer_group_1", new ProductPriceGroup() { group_price = new ProductGroupPrice { price = "150", price_type = "currency" } });
serObj.meta_data[0].value.Add("customer_group_2", new ProductPriceGroup() { group_price = new ProductGroupPrice { price = "125", price_type = "currency" } });
var jss = new JavaScriptSerializer();
var result = jss.Serialize(serObj);
Console.WriteLine(result);

生成的JSON(我将其格式化以进行比较,实际生成是单行/没有缩进/间距):

{
  "meta_data": [
  {
    "id":220910,
    "key":"rbp_role_config",
    "value": {
      "customer_group_1": {
        "group_price": {
          "price":"150",
          "price_type":"currency"
        }
      },
      "customer_group_2": { 
        "group_price": {
          "price":"125",
          "price_type":"currency"
        }
      }
    }
  }]
}