当前位置: 动力学知识库 > 问答 > 编程问答 >

How to create a serialized JSON object in c#

问题描述:

Hi I want to create the following:

{

"RetailerMappings": {

"Title": "unwanted HR186320 Philips VivaCollection juicer HR1863/20",

"ModelName": "HR186320 Philips VivaCollection juicer HR1863/20"

},

"ManufacturerId": 14,

"RetailerId": 652,

"SaveMapping": false

}

First if all I did the following:

//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

});

However this returns the following:

{

"RetailerMappings":"

{\"ManufacturerMappingField\":\"ModelName\",

\"RetailerMappingField\":\"Title\"}",

"ManufacturerId":114,

"RetailerId":2593,

"SaveMapping":false

}

So I'm not sure how to get:

"RetailerMappings": {

"Title": "unwanted HR186320 Philips VivaCollection juicer HR1863/20",

"ModelName": "HR186320 Philips VivaCollection juicer HR1863/20"

},

As Title and ModelName depends on the mapping rules:

mappingRule.ManufacturerMappingField,

mappingRule.RetailerMappingField

and depending on the mapping rule I need to get values from:

foreach (var row in dataRows)

which is the outer loop..

so for example if

mappingRule.ManufacturerMappingField is Title I would use:

Title = row.Title,

I hope what I m asking makes sense.

Thanks

Edit:

 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

...

and a model:

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; }

}

}

Actually I think I'm overcomplicating things

The following should work:

 json = new JavaScriptSerializer().Serialize(new

{

RetailerMappings = row,

ManufacturerId = manufacturer.Id,

RetailerId = retailer.Id,

SaveMapping = false

});

网友答案:

With json.net you can just serialize the following, I assume JavaScriptSerializer should give similar results (if not, consider switching to 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
}
网友答案:

Using Json.NET https://www.nuget.org/packages/Newtonsoft.Json/

Modify your model to match the output you want.

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
}
网友答案:

Thank you to everyone who had a look at this.

The solution that I found was as follows:

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

this was because row contained everything that I needed.

However, if it didn't and I had to create the pairing from scratch the following also works (I have had to use it in a different are of the code)

  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
            });

Where vm.RetailerMappingField.ToString() is the retailermapping value I need to get I.e Title / ModelName /SKU

and teststring is the value which needs to go in the mapping field.

分享给朋友:
您可能感兴趣的文章:
随机阅读: