小编Sta*_*bra的帖子

使用 System.Text.Json.Serialization 将动态对象转换为 json 时抛出异常

我想将动态对象转换为 json 字符串。当我过去使用 Newtonsoft.Json 时,它工作得很好。当我将 .net core 升级到 3.0 并使用 System.Text.Json 时,它很糟糕。

看代码:

using System;
using System.Collections.Generic;
using System.Dynamic;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic product = new ExpandoObject();
            product.ProductName = "Elbow Grease";
            product.Enabled = true;
            product.Price = 4.90m;
            product.StockCount = 9000;
            product.StockValue = 44100;
            product.Tags = new string[] { "Real", "OnSale" };

            // Will output: { "ProductName":"Elbow Grease","Enabled":true,"Price":4.90,
            // "StockCount":9000,"StockValue":44100,"Tags":["Real","OnSale"]}
            var json1 = Newtonsoft.Json.JsonConvert.SerializeObject(product);
            Console.WriteLine(json1);

            // Both will throw exception: System.InvalidCastException:“Unable to
            // …
Run Code Online (Sandbox Code Playgroud)

c# .net-core system.text.json

5
推荐指数
1
解决办法
1437
查看次数

标签 统计

.net-core ×1

c# ×1

system.text.json ×1