从JSON字符串中读取所有动态名称和值(Read all dynamic name and value from JSON string)

编程入门 行业动态 更新时间:2024-10-12 05:51:18
从JSON字符串中读取所有动态名称和值(Read all dynamic name and value from JSON string)

我需要从JSON字符串中获取所有动态名称和值。 我将使用JSON字符串参数创建一个函数。 该参数JSON字符串名称和值可以更改,但我需要从该JSON字符串打印所有名称和值。

示例代码:

json : { "data": [{ "id": "001", "Name": "Somu", "Address": "Erode", }, { "id": "002", "Name": "Ajal", "Address": "USA", }] }

我想通过in循环获取此JSON的所有值。 属性名称可能会更改或增加属性count.I需要从传递的JSON中获取所有值。

Expected Result : 1 st loop Id = 001 Name =Somu Address =Erode 2 nd loop Id = 002 Name =Ajal Address =USA

I need to get all dynamic name and values from JSON string. I am going to create one function with JSON string parameter. that parameter JSON string name and values can change, But I need to print all names and values from that JSON string.

Example code :

json : { "data": [{ "id": "001", "Name": "Somu", "Address": "Erode", }, { "id": "002", "Name": "Ajal", "Address": "USA", }] }

I want to Get all values from this JSON with in loop. Property name may change or increase property count.I need to get all values from passed JSON.

Expected Result : 1 st loop Id = 001 Name =Somu Address =Erode 2 nd loop Id = 002 Name =Ajal Address =USA

最满意答案

使用Json.Net

string json = @"{ ""data"": [ { ""id"": ""001"", ""Name"": ""Somu"", ""Address"": ""Erode"", }, { ""id"": ""002"", ""Name"": ""Ajal"", ""Address"": ""USA"", }] }"; var result = JObject.Parse(json) ["data"] .Select(x => new { id = (string)x["id"], Name = (string)x["Name"], Address = (string)x["Address"], }) .ToList();

或更多动态版本

var result = JObject.Parse(json) ["data"] .Select(x=> x.Children().Cast<JProperty>() .ToDictionary(p=>p.Name,p=>(string)p.Value)) .ToList();

var result = JObject.Parse(json)["data"] .ToObject<List<Dictionary<string,string>>>();

Using Json.Net

string json = @"{ ""data"": [ { ""id"": ""001"", ""Name"": ""Somu"", ""Address"": ""Erode"", }, { ""id"": ""002"", ""Name"": ""Ajal"", ""Address"": ""USA"", }] }"; var result = JObject.Parse(json) ["data"] .Select(x => new { id = (string)x["id"], Name = (string)x["Name"], Address = (string)x["Address"], }) .ToList();

or more dynamic versions

var result = JObject.Parse(json) ["data"] .Select(x=> x.Children().Cast<JProperty>() .ToDictionary(p=>p.Name,p=>(string)p.Value)) .ToList();

.

var result = JObject.Parse(json)["data"] .ToObject<List<Dictionary<string,string>>>();

更多推荐

本文发布于:2023-07-15 05:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110772.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   名称   动态   JSON   dynamic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!