Loading

C# JSON动态解析

Dictionary<string, object> suggestions = JSONSerializer.Deserialize<Dictionary<string, object>>(jsonStudent)


if (suggestions.Keys.Contains("UserId"))
{
student["new_mduserid"] = suggestions["UserId"].ToString();//MD用户Id
}


多数组的可以用 List<Dictionary<string, object>>

 

 

try {
string json = File.ReadAllText("robotv1.json");
// 解析json文件
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonObj.Lidar.DefaultBaud);
// 也可以修改
jsonObj.Lidar.DefaultBaud = 123;
//重修序列化
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
//保存
File.WriteAllText("config.json", output);
}catch {}

 

 

 

static void Main(string[] args)
        {
            string jsonData = "{\"name\":\"lily\",\"age\":23,\"addr\":{\"city\":\"guangzhou\",\"province\":\"guangdong\"}}";
            parseToJObject_1(jsonData);
            Console.ReadLine();

        }

        private static void parseToJObject_1(string jsonData)
        {
            JObject jsonObj = JObject.Parse(jsonData);
            string name = jsonObj["name"].ToString();
            string age = jsonObj["age"].ToString();
            string city = ((JObject)jsonObj["addr"])["city"].ToString();
            string province = ((JObject)jsonObj["addr"])["province"].ToString();
            Console.WriteLine("name={0},age={1},city={2},province={3}{4},", name, age, city, province,System.Environment.NewLine);

        }


https://github.com/SlimeNull/CHO.Json
posted @ 2021-03-04 09:34  jevan  阅读(756)  评论(0编辑  收藏  举报