json 如何解析ValueKind = Object:{}在没有NewtonSoft的情况下使用动态对象时?

xam8gpfp  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(543)

有效负载进入parts.model,它被称为Dynamic,因为它是一个由多个端点使用的服务。因此,我试图保留结构,同时试图解决ValueKind = Object问题。
这就是我试图转换回动态的模型。

"Model": {
        "CustomerSurname": "Johnson",
        "Title": "Mr",
        "PlanType": "Help Extension",
        "ServiceAdvisor": "Jeff Matle",
        "DealershipName": "Goldwagen Pretoria"
    },

我尝试使用JsonSerializer.Deserialize多次,但它不起作用。

public async Task<IActionResult> SendSms([FromBody] CreatePart parts)
        {
            parts.DateMessageScheduled = DateTime.Now;
            parts.DateCutOff = DateTime.MaxValue;
            parts.CommunicationTypeId = CommunicationType.Codes.SMS;

            dynamic obj = parts.Model;

            JsonElement jsonString = obj;

            var dynamicObject = JsonSerializer.Deserialize<JsonElement>(jsonString);

            var result = await _createNewPartService.Post(parts);

            return new JsonResult(result);
        }

dynamicObject的结果:

ValueKind = Object : "{
        "CustomerSurname": "Johnson",
        "Title": "Mr",
        "PlanType": "Help Extension",
        "ServiceAdvisor": "Jeff Matle",
        "DealershipName": "Goldwagen Pretoria"
    }"
erhoui1w

erhoui1w1#

试试这个代码

var dict = System.Text.Json
          .JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(json);

    dynamic dynamicObj = new ExpandoObject();
    foreach (var item in dict)
    {
        dynamic innerObj = new ExpandoObject();
        foreach (var word in item.Value)
            ((IDictionary<string, object>)innerObj).Add(word.Key, word.Value);

        ((IDictionary<string, object>)dynamicObj).Add(item.Key, innerObj);
    }

    Console.WriteLine(dynamicObj.Model.Title);

但正如@Dai在评论中所写的那样,“仅仅因为你能做到这一点,并不意味着你应该这样做”

相关问题