将 .json 文件加载到 C# 程序中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18538428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:30:26  来源:igfitidea点击:

Loading a .json file into c# program

c#json

提问by ford prefect

I am trying to move my website from XML based config files to JSON based ones. Is there a way to load in a .jsonfile in so that it turns into the object? I have been searching the web and I cannot find one. I already have the .xmlfile converted and saved as a .json. I would rather not use a 3rd party library.

我正在尝试将我的网站从基于 XML 的配置文件移动到基​​于 JSON 的配置文件。有没有办法加载.json文件以使其变成对象?我一直在网上搜索,我找不到一个。我已经将.xml文件转换并保存为.json. 我宁愿不使用第 3 方库。

采纳答案by STW

You reallyshould use an established library, such as Newtonsoft.Json(which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.

确实应该使用一个已建立的库,例如Newtonsoft.Json(甚至 Microsoft 也将其用于 MVC 和 WebAPI 等框架)或 .NET 的内置JavascriptSerializer

Here's a sample of reading JSON using Newtonsoft.Json:

下面是使用 Newtonsoft.Json 读取 JSON 的示例:

JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));

// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
  JObject o2 = (JObject) JToken.ReadFrom(reader);
}

回答by Seth Flowers

See Microsofts JavaScriptSerializer

参见微软的JavaScriptSerializer

The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.

异步通信层在内部使用 JavaScriptSerializer 类来序列化和反序列化在浏览器和 Web 服务器之间传递的数据。您无法访问序列化程序的该实例。但是,此类公开了公共 API。因此,当您想要在托管代码中使用 JavaScript 对象表示法 (JSON) 时,可以使用该类。

Namespace: System.Web.Script.Serialization

命名空间:System.Web.Script.Serialization

Assembly: System.Web.Extensions (in System.Web.Extensions.dll)

程序集:System.Web.Extensions(在 System.Web.Extensions.dll 中)

回答by evanmcdonnal

As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;

正如其他答案中提到的,我建议使用 json.NET。可以使用 NuGet 下载包。然后将您的 json 文件反序列化为 C# 对象,您可以执行以下操作;

   JsonSerializer serializer = new JsonSerializer();
   MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(@".\path\to\json\config\file.json");

The above code assumes that you have something like

上面的代码假设你有类似的东西

public class MyObject
{
    public string prop1 { get; set; };
    public string prop2 { get; set; };
}

And your json looks like;

你的 json 看起来像;

{
      "prop1":"value1",
      "prop2":"value2"
}

I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.

我更喜欢使用通用的 deserialize 方法,该方法将 json 反序列化为一个对象,假设您提供的类型与 json 的定义匹配。如果两者之间存在差异,它可能会抛出,或者不设置值,或者只是忽略 json 中的内容,这取决于问题是什么。如果 json 定义与 C# 类型定义完全匹配,那么它就可以工作。

回答by ford prefect

Another good way to serialize json into c# is below:

将 json 序列化为 c# 的另一种好方法如下:

RootObject ro = new RootObject();
     try
    {

        StreamReader sr = new StreamReader(FileLoc);
        string jsonString = sr.ReadToEnd();
        JavaScriptSerializer ser = new JavaScriptSerializer();
        ro = ser.Deserialize<RootObject>(jsonString);


   }

you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client

您需要在 .net 4.0 中添加对 system.web.extensions 的引用,这是在程序文件(x86)> 参考程序集> 框架> system.web.extensions.dll 中,并且您需要确保您使用的是常规 4.0框架不是 4.0 客户端

回答by Shakir Ahamed

Use Server.MapPath to get the actual path of the JSON file and load and read the file using StreamReader

使用 Server.MapPath 获取 JSON 文件的实际路径并使用 StreamReader 加载和读取文件

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class RootObject
{
    public string url_short { get; set; }
    public string url_long { get; set; }
    public int type { get; set; }
}

public class Program
{
    static public void Main()
    {
       using (StreamReader r = new StreamReader(Server.MapPath("~/test.json")))
       {
           string json = r.ReadToEnd();
           List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json);
       }

    Console.WriteLine(ro[0].url_short);                 
    }  
}

Note : Look below link also I have answered for question similar to this.It will be help full for you How to Parse an example string in C#

注意:看下面的链接,我也回答了类似的问题。这对你很有帮助 如何解析 C# 中的示例字符串

回答by Deepak Shaw

I have done it like:

我已经这样做了:

            using (StreamReader sr = File.OpenText(jsonFilePath))
            {
                var myObject = JsonConvert.DeserializeObject<List<YourObject>>(sr.ReadToEnd());
            }

also, you can do this with async call like: sr.ReadToEndAsync(). using Newtonsoft.Json as reference.

此外,您可以使用异步调用来执行此操作,例如:sr.ReadToEndAsync()。使用 Newtonsoft.Json 作为参考。

Hope, this helps.

希望这可以帮助。