-1

I found a problem, and I am interested what would be the best solution to create from a JsonResult object a JObject. The JsonResult is created like this:

Json(new
{
    productId,
    gtin,
    mpn,
    sku,
    price,
    basepricepangv,
    stockAvailability,
    enabledattributemappingids = enabledAttributeMappingIds.ToArray(),
    disabledattributemappingids = disabledAttributeMappingIds.ToArray(),
    pictureFullSizeUrl,
    pictureDefaultSizeUrl,
    isFreeShipping,
    message = errors.Any() ? errors.ToArray() : null
});

It's value looks like this in string representation:

var jsonResult = "{ productId = 1, gtin = null, mpn = null, sku = null, price = \"$25.00\", basepricepangv = null, stockAvailability = \"\", enabledattributemappingids = {int[0]}, disabledattributemappingids = {int[0]} }";

I need to change some properties in this ,,json,,. Because it is not valid json string, I can't deserialize it. Are there any built-in library or other solution to do this. thnx

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Wasyster
  • 2,279
  • 4
  • 26
  • 58
  • https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.jsonresult.value?view=aspnetcore-6.0#microsoft-aspnetcore-mvc-jsonresult-value – ProgrammingLlama Sep 24 '22 at 06:15
  • I need to change some properties in this ,,json,,. can you tell what does it mean? – Serge Sep 24 '22 at 10:38

2 Answers2

0
private static readonly JsonSerializerSettings defaultSettings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            TypeNameHandling = TypeNameHandling.None,
            ContractResolver = new DefaultContractResolver(),
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            DateFormatString = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK",
    };

public static string ToJson(this object o) =>
            o != null ? JsonConvert.SerializeObject(o, defaultSettings) : null;
Wasyster
  • 2,279
  • 4
  • 26
  • 58
0

to get a valid json you need

var json = JsonConvert.SerializeObject(new
{
    productId,
    gtin,
    mpn,
    sku,
    price,
    basepricepangv,
    stockAvailability,
    enabledattributemappingids = enabledAttributeMappingIds.ToArray(),
    disabledattributemappingids = disabledAttributeMappingIds.ToArray(),
    pictureFullSizeUrl,
    pictureDefaultSizeUrl,
    isFreeShipping,
    message = errors.Any() ? errors.ToArray() : null
});

return new JsonResult(json);
Serge
  • 40,935
  • 4
  • 18
  • 45