如何在c#中创建序列化的JSON对象

时间:2015-10-26 11:50:15

标签: c# json

您好我想创建以下内容:

{
    "RetailerMappings": {
        "Title": "unwanted HR186320 Philips VivaCollection juicer HR1863/20",
        "ModelName": "HR186320 Philips VivaCollection juicer HR1863/20"
    },
    "ManufacturerId": 14,
    "RetailerId": 652,
    "SaveMapping": false
}

首先,如果我做了以下所有事情:

//first get the mapping rules:
string jsonRetailerMappings = "";
jsonRetailerMappings = new JavaScriptSerializer().Serialize(new
{
    mappingRule.ManufacturerMappingField,
    mappingRule.RetailerMappingField

});

string json = "";

//Create the JSON body request:
json = new JavaScriptSerializer().Serialize(new
{
    RetailerMappings =jsonRetailerMappings,
    ManufacturerId = manufacturer.Id,
    RetailerId = retailer.Id,
    SaveMapping = false
});

然而,这会返回以下内容:

{
"RetailerMappings":"
{\"ManufacturerMappingField\":\"ModelName\",
\"RetailerMappingField\":\"Title\"}",
"ManufacturerId":114,
"RetailerId":2593,
"SaveMapping":false
}

所以我不确定如何获得:

"RetailerMappings": {
        "Title": "unwanted HR186320 Philips VivaCollection juicer HR1863/20",
        "ModelName": "HR186320 Philips VivaCollection juicer HR1863/20"
    },

由于Title和ModelName取决于映射规则:

mappingRule.ManufacturerMappingField,
mappingRule.RetailerMappingField

并且根据映射规则,我需要从以下位置获取值:

foreach (var row in dataRows)

这是外循环.. 例如,如果 mappingRule.ManufacturerMappingField是我将使用的标题:

Title = row.Title,

我希望我提出的问题是有道理的。

由于

编辑:

  foreach (var row in dataRowsNamesUs)
            {
                try
                {                  

                        #region replaceWithAPIcall
                        //New Auto Mapper
                        Product autoMapped = null;
                        if (rpmn == null && manufacturerRetailer != null && manufacturerRetailer.UseAutoMapper)
                        {
                            var mappingRules = autoMapperRuleRepository.GetAutoMapperRulesByManufacturerRetailer(file.ManufacturerId, file.RetailerId).OrderBy(r => r.Ordering).ToList();

                            foreach (var mappingRule in mappingRules)
                            {
                                try
                                {
                                    //old --  autoMapped = autoMapper.GetMapping(row, possibleMatches, mappingRule);

                                    //new api request: (change this to proper url (config setting))
                                    var apiUrl = "http://localhost:49347/api/map";


                                    //first get the mapping rules:
                                    string jsonRetailerMappings = "";
                                    jsonRetailerMappings = new JavaScriptSerializer().Serialize(new
                                    {
                                        mappingRule.ManufacturerMappingField,
                                        mappingRule.RetailerMappingField

                                    });

                                    string json = "";

                                    //Create the JSON body request:
                                    json = new JavaScriptSerializer().Serialize(new
                                    {
                                        RetailerMappings =jsonRetailerMappings,
                                        ManufacturerId = manufacturer.Id,
                                        RetailerId = retailer.Id,
                                        SaveMapping = false
                                    });

                                    string result = "";
                                    using (var client = new WebClient())
                                    {
                                        client.Headers[HttpRequestHeader.ContentType] = "application/json";
                                        result = client.UploadString(apiUrl, "POST", json);
                                    }
                                    //this will need to be changed to automapped success..
                                    Console.WriteLine(result);
                                }
                                catch (Exception ex)
                                {
                                    Logger.Warn("Failed to auto map.", ex);
                                }
                                if (autoMapped != null)
                                {
                                    break;
                                }
                            }
                        #endregion replaceWithAPIcall
...

和模特:

namespace Automapper.Core.Models
{
    public class MappingParameters
    {
        public Dictionary<RetailerProductMappingField, string> RetailerMappings { get; set; }
        public int ManufacturerId { get; set; }
        public int RetailerId { get; set; }
        public bool SaveMapping { get; set; }
    }
}

其实我觉得我过于复杂了

以下内容应该有效:

   json = new JavaScriptSerializer().Serialize(new
                                    {
                                        RetailerMappings = row,
                                        ManufacturerId = manufacturer.Id,
                                        RetailerId = retailer.Id,
                                        SaveMapping = false
                                    });

3 个答案:

答案 0 :(得分:2)

使用json.net,您可以序列化以下内容,我假设JavaScriptSerializer应该给出类似的结果(如果没有,请考虑切换到json.net):

new 
{
    RetailerMappings = new
    {
       Title = "unwanted HR186320 Philips VivaCollection juicer HR1863/20",
       ModelName = "HR186320 Philips VivaCollection juicer HR1863/20"
    },
    ManufacturerId = 14,
    RetailerId =  652,
    SaveMapping = false
}

答案 1 :(得分:0)

使用Json.NET https://www.nuget.org/packages/Newtonsoft.Json/

修改模型以匹配您想要的输出。

class MappingParameters
{
    public RetailerMappings RetailerMappings { get; set; }
    public int ManufacturerId { get; set; }
    public int RetailerId { get; set; }
    public bool SaveMapping { get; set; }
}

class RetailerMappings
{
    public string Title { get; set; }
    public string ModelName { get; set; }
}
MappingParameters mapping = new MappingParameters();
mapping.RetailerMappings = new RetailerMappings();
mapping.RetailerMappings.Title = "unwanted HR186320 Philips VivaCollection juicer HR1863/20";
mapping.RetailerMappings.ModelName = "HR186320 Philips VivaCollection juicer HR1863/20";
mapping.ManufacturerId = 14;
mapping.RetailerId = 652;
mapping.SaveMapping = false;
string json = JsonConvert.SerializeObject(mapping);
{
    "RetailerMappings": {
       "Title": "unwanted HR186320 Philips VivaCollection juicer HR1863/20",
       "ModelName": "HR186320 Philips VivaCollection juicer HR1863/20"
    },
    "ManufacturerId": 14,
    "RetailerId": 652,
    "SaveMapping": false
}

答案 2 :(得分:0)

感谢所有看过这个的人。

我找到的解决方案如下:

   json = new JavaScriptSerializer().Serialize(new
                                    {
                                        RetailerMappings = row,
                                        ManufacturerId = manufacturer.Id,
                                        RetailerId = retailer.Id,
                                        SaveMapping = false
                                    });

这是因为行包含了我需要的所有内容。

但是,如果它没有,我必须从头开始创建配对,以下也可以(我必须在不同的代码中使用它)

  Dictionary<string, string> retailerMappingDictionary = new Dictionary<string, string>();
            retailerMappingDictionary.Add(vm.RetailerMappingField.ToString(), testString);

 json = new JavaScriptSerializer().Serialize(new
            {
                RetailerMappings = retailerMappingDictionary,
                ManufacturerId = vm.ManufacturerId,
                RetailerId = vm.RetailerId,
                SaveMapping = false
            });

其中vm.RetailerMappingField.ToString()是我需要获得的零售价值I.e Title / ModelName / SKU

和teststring是需要在映射字段中输入的值。