簡體   English   中英

JsonResult object 到 JObject

[英]JsonResult object to JObject

我發現了一個問題,我很感興趣從JsonResult object 和JObject創建的最佳解決方案是什么。 JsonResult是這樣創建的:

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

它的值在字符串表示中如下所示:

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

我需要更改其中的一些屬性,json,,。 因為它不是有效的 json 字符串,我無法反序列化它。 是否有任何內置庫或其他解決方案可以做到這一點。 謝謝

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;

要獲得您需要的有效 json

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM