Home > front end >  JsonResult object to JObject
JsonResult object to JObject

Time:09-26

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

CodePudding user response:

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;

CodePudding user response:

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);
  • Related