如何解析动态字符串中的键值对并映射到指定C#模型
JSON解析为指定C#模型的实现方案
可以将给定的JSON解析为你定义的C#模型,但需要做适配处理——原JSON的每个数组元素是仅包含一个动态键的对象,无法直接映射到带固定key/value属性的模型,需通过中间转换实现。
步骤1:修正并定义C#模型
首先补全模型的类定义(原代码缺少class关键字):
public class KeyValueModel { public string key { get; set; } public string value { get; set; } }
步骤2:使用JSON库完成解析与转换
方案一:使用Newtonsoft.Json(第三方库)
using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; // 原始JSON字符串 string rawJson = "[{\"C74\": \"123\"}, {\"C75\": \"32\"}, {\"C76\": \"11\"}, {\"C78\": \"15\"}]"; // 先解析为字典列表 var dictList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(rawJson); // 转换为目标模型列表 List<KeyValueModel> modelList = dictList.Select(dict => new KeyValueModel { key = dict.Keys.First(), value = dict.Values.First() }).ToList();
方案二:使用System.Text.Json(.NET内置库)
using System.Text.Json; using System.Collections.Generic; using System.Linq; string rawJson = "[{\"C74\": \"123\"}, {\"C75\": \"32\"}, {\"C76\": \"11\"}, {\"C78\": \"15\"}]"; var dictList = JsonSerializer.Deserialize<List<Dictionary<string, string>>>(rawJson); List<KeyValueModel> modelList = dictList.Select(dict => new KeyValueModel { key = dict.Keys.First(), value = dict.Values.First() }).ToList();
核心逻辑说明
原JSON的每个元素是单键值对的独立对象,我们先将其解析为Dictionary<string, string>类型,再提取字典中的唯一键和值,分别赋值给KeyValueModel的key和value属性,最终得到目标模型的集合。
内容的提问来源于stack exchange,提问作者imcmjha
相关产品推荐
相关产品推荐

