You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#用Newtonsoft反序列化Python输出JSON报JsonSerializationException如何解决

问题根因

你Python代码中生成的JSON结构和C# WordVector 类的结构不匹配:

  • Python代码用jsons.append((i,jas))存入元组,最终dumps输出的是二维数组结构,示例格式如下:
    [["nice", [0.11, 0.23, 0.45]], ["love", [0.32, 0.56, 0.78]]]
    
  • Newtonsoft.Json 反序列化WordVector类时要求每个元素是带键名的JSON对象,而非数组,因此抛出类型不匹配错误,和跨语言处理逻辑无关。

修复方案(优先选方案1)

方案1:调整Python输出结构(推荐,改动量最小)

修改Python代码中生成列表的逻辑,把元组替换为带对应键名的字典,直接输出符合C#类结构的JSON对象数组:

for i in wor:
    jas = extractword(w,i)
    jsons.append({
        "weights": jas,
        "json": i,
        "wordVectorResult": 0 # 此处填和C# WordVectorResult枚举对应的成功状态数值即可
    })

同时给C#的WordVector类添加无参构造函数,否则Newtonsoft反序列化时无法实例化对象:

public class WordVector
{
    // 新增无参构造
    public WordVector(){}

    // 原有属性、构造函数保持不变
    public float[] weights { get; set; }
    public string json { get; set; }
    public WordVectorResult WordVectorResult { get; set; }

    public WordVector(float[] weights, WordVectorResult result, string json)
    {
        this.weights = weights;
        this.WordVectorResult = result;
        this.json = json;
    }

    public WordVector(WordVectorResult result)
    {
        this.WordVectorResult = result;
    }
}

改完之后原有C#反序列化代码可以直接正常运行。


方案2:不改Python代码,C#端手动映射

如果无法修改Python代码,可以先把JSON反序列化为嵌套数组,再手动映射为WordVector对象:

// 先反序列化为嵌套数组结构
var rawData = JsonConvert.DeserializeObject<List<object[]>>(result);
// 手动映射为WordVector数组
WordVector[] vectors = rawData.Select(item => new WordVector
{
    json = item[0].ToString(),
    weights = (item[1] as JArray).ToObject<float[]>(),
    WordVectorResult = WordVectorResult.Success // 自行赋值对应枚举状态
}).ToArray();

注意事项

如果WordVectorResult是枚举类型,反序列化时出现不匹配问题,可以给属性加[JsonConverter(typeof(StringEnumConverter))]特性,或者确保Python输出的枚举数值和C#端定义一致。

内容的提问来源于stack exchange,提问作者lakshya 'Coding' Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:45:02