繁体   English   中英

"将 json 转换为 C# 数组?"

[英]Convert json to a C# array?

有谁知道如何将包含 json 的字符串转换为 C# 数组。 我有这个从 webBrowser 读取 text/json 并将其存储到字符串中。

string docText = webBrowser1.Document.Body.InnerText;

只需要以某种方式将该 json 字符串更改为一个数组。 一直在看 Json.NET,但我不确定这是否是我需要的,因为我不想将数组更改为 json; 但反过来。 谢谢您的帮助!

只需获取字符串并使用 JavaScriptSerializer 将其反序列化为本机对象。 例如,有这个 json:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

您需要创建一个 C# 类,例如,定义为 Person 的类:

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

您现在可以通过执行以下操作将 JSON 字符串反序列化为 Person 数组:

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

这是JavaScriptSerializer 文档链接

注意:我上面的代码没有经过测试,但这就是测试它的想法 除非你正在做一些“异国情调”的事情,否则你应该可以使用 JavascriptSerializer。

是的,Json.Net 正是您所需要的。 您基本上想将 Json 字符串反序列化为objects数组。

他们的例子

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);
using Newtonsoft.Json;

在包控制台中安装这个类 这个类在所有 .NET 版本中都可以正常工作,例如在我的项目中:我有 DNX 4.5.1 和 DNX CORE 5.0,一切正常。

首先在JSON反序列化之前,你需要声明一个类来正常读取并在某处存储一些数据这是我的类:

public class ToDoItem
{
    public string text { get; set; }
    public string complete { get; set; }
    public string delete { get; set; }
    public string username { get; set; }
    public string user_password { get; set; }
    public string eventID { get; set; }
}

在您通过 GET 请求请求数据的 HttpContent 部分中,例如:

HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync();
//deserialization in items
ToDoItem[] items = JsonConvert.DeserializeObject<ToDoItem[]>(mycontent);

老问题,但如果使用 .NET Core 3.0 或更高版本,则值得添加答案。 JSON 序列化/反序列化内置于框架 (System.Text.Json) 中,因此您不必再使用第三方库。 这是一个基于@Icarus 给出的最佳答案的示例

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}

其他响应中未涵盖的一种情况是您不知道 JSON 对象包含的类型。 这就是我的情况,因为我需要能够不输入它并让它保持动态。

var objectWithFields =  js.Deserialize<dynamic[]>(json);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM