Привет Я хочу, чтобы создать следующее:Как создать упорядоченный объект JSON в C#
{
"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"
},
Как Название и ModelName зависят от правил отображения:
mappingRule.ManufacturerMappingField,
mappingRule.RetailerMappingField
и в зависимости от правила отображения, мне нужно, чтобы получить значения из:
foreach (var row in dataRows)
, который является внешним контуром .. так например, если mappingRule.ManufacturerMappingField - это название Я бы использовал:
Title = row.Title,
Надеюсь, что я спрашиваю, имеет смысл.
Благодаря
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
...
и модель:
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
});
JSON.NET был бы полезен, я бы проецировал вашу информацию, используя отбор в анонимные объекты –
Это не имеет особого смысла. Пожалуйста, опубликуйте полное, минимальное воспроизведение вашей проблемы. Мы не знаем, что означает * внешний цикл * в вашем коде. Без достаточной информации мы не можем помочь. –
У вас есть модель, поддерживающая это? –