繁体   English   中英

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

[英]How do Serialize this C# object to JSON?

这是我想要的输出:

  "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表中获取值“ customer_group_1”,“ customer_group_2”等,因此它们必须是动态属性。

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

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,但是由于某种原因,在尝试将其添加到产品的meta数据属性时,我遇到了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; }

尝试将元数据对象添加到此列表时,出现“发生类型'System.NullReferenceException'的第一次机会异常”。 “ p”是产品对象。 我检查过,p不为空,productMeta不为空。

p.meta_data.Add(productMeta);

编辑:我很傻,忘了为meta_data属性新建一个列表...

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

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

全部做完! 谢谢您的帮助!

看起来并不那么困难,只需生成一个与您的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"
        }
      }
    }
  }]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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