将JSON数据转换为对象

时间:2022-10-24 17:28:24

I am very new to this.Pardon me if I make any mistakes.

我对此很陌生。如果我犯了任何错误,请原谅我。

I have data in JSON form.Can I read this data directly and use it in C# code ?

我有JSON格式的数据。我可以直接读取这些数据并在C#代码中使用它吗?

From what I understood from reading up on the internet,I think I have to convert it into an object form to use the data.Am I right ?

根据我在互联网上阅读的理解,我认为我必须将其转换为对象形式才能使用数据。对吧?

If yes,Then I saw this method to convert as below :

如果是,那么我看到这个方法转换如下:

string data = JsonConvert.DeserializeObject<string>(getmyissue());

getmyissue is the function which returns a string which has data in json format.

getmyissue是一个函数,它返回一个包含json格式数据的字符串。

This gives me an exception saying

这给了我一个例外

"Error reading string.Unexpected Token."

“读取字符串时出错。意外的令牌。”

Can someone guide me where am I going wrong ?

有人可以指导我哪里出错了吗?

EDIT

MyIssue.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example
{
    public class MyIssue
    {
        public string name{get;set;}
        public string description { get; set; }
        public string created { get;set; }
        public string updated{get;set;}
        public string displayName { get; set; }

    }
}

Program.cs

MyIssue obj=null;
        try
        {             
            obj = JsonConvert.DeserializeObject<MyIssue>(manager.getmyissue());
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.WriteLine("Name:  "+obj.name);

2 个解决方案

#1


The easiest way to de-serialize Json in a C#/.NET program is to use the brilliant NewtonSoft JSON library.

在C#/ .NET程序中对Json进行反序列化的最简单方法是使用出色的NewtonSoft JSON库。

There are numerous ways to do it, but I have to admit that the NS libs just get on with the task (and no I'm not a member of the team etc, just an Avid User :-) ).

有很多方法可以做到这一点,但我不得不承认NS库只是继续执行任务(而且我不是团队的成员等,只是一个Avid用户:-))。

To do what you want for example, if you had:

要做你想做的事,例如,如果你有:

{'Name': 'A person', 'AllowAccess': true,'Areas': ['Sales','Admin']}

You would first build an object to represent it as follows:

您将首先构建一个对象来表示它,如下所示:

public MyObject
{
  public string Name { get; set; }
  public bool AllowAccess { get; set; }
  public List<string> Areas { get; set; }
}

Once you've done this, it's a simple case of just doing the following:

完成此操作后,只需执行以下操作即可:

string jsonString = "// Your json formated string data goes here";
MyObject myObject = JsonConvert.DeserializeObject<MyObject>(jsonString);

The properties in your object should at that point, reflect the properties in the JSON data you sent to it.

对象中的属性应该在此时反映您发送给它的JSON数据中的属性。

You will of course need to add the NS JSON Libs to your project, either via NuGet or Manually, which ever is easier for you, everything you need to know about that is here:

您当然需要通过NuGet或Manually将NS JSON Libs添加到您的项目中,这对您来说更容易,您需要了解的所有内容如下:

How to install JSON.NET using NuGet?

如何使用NuGet安装JSON.NET?

The really good thing about NS JSON however is not the ease of use, but the fact that it can also do dynamic de-serialization.

然而,NS JSON真正的好处不是易用性,而是它还可以进行动态反序列化。

This comes in handy if you've no idea what to expect in the JSON you receive, and so don't know ahead of time how to construct an object to hold the results.

如果你不知道你收到的JSON有什么期望,那么这就派上用场了,所以不要提前知道如何构造一个对象来保存结果。

Rather than repeat what others have said however, you can find more information of doing things dynamically in this stack overflow post:

然而,您可以在此堆栈溢出帖子中找到有关动态执行操作的更多信息,而不是重复其他人所说的内容:

Deserializing JSON using JSon.NET with dynamic data

使用带动态数据的JSon.NET反序列化JSON

Update

Looking at your JSON data you have way more fields/properties in there than your trying to parse, and none of the libraries in common use (To the best of my knowledge) will pick and choose the fields to copy, you either have an object that represents them all, or not at all, the later of which I believe is the problem your facing.

查看你的JSON数据,你有更多的字段/属性,而不是你想要解析的,并且没有一个常用的库(据我所知)将挑选并选择要复制的字段,你要么有一个对象这代表了他们所有人,或根本不代表他们,我认为这是你面临的问题。

I have a rather neat "JSON" plug in for chrome, than when given a chunk of JSON data formats the output for me nicely and makes it easy to read, it also helps massively when defining objects, allowing you to see the full nested structure of your data, here are a series of images showing your JSON data formatted using this plugin:

我有一个相当简洁的“JSON”插件用于chrome,比给我一大块JSON数据格式输出对我很好并且易于阅读,它也有助于大量定义对象,让你看到完整的嵌套结构您的数据,这里有一系列图像显示您使用此插件格式化的JSON数据:

将JSON数据转换为对象

将JSON数据转换为对象

I'm not going to paste anymore images in, but that goes on for another 4 pages!!

我不打算再粘贴图片了,但这还有4页!!

Now, some extra information that may help you.

现在,一些可能对您有帮助的额外信息。

I know from experience (I had to write a parser in PHP for these Jira webhooks) that within the Jira control panel, you can configure your webhooks to ONLY return the information your interested in.

我从经验中知道(我必须在PHP中为这些Jira webhooks编写一个解析器),在Jira控制面板中,您可以配置您的webhook只返回您感兴趣的信息。

Right now, it looks like you've just told the system to dump everything, for every event that you've hooked too (Which looks like - all of them), it's been a while since I did any work with these, but as well as a global webhook, you also have individual webhooks, which only fire on specific events and produce JSON data that's very much smaller than what your dealing with here.

现在,看起来你刚刚告诉系统转​​储所有内容,对于你所挂钩的每个事件(看起来都像 - 所有这些),已经有一段时间了,因为我做了这些工作,但是作为一个全球webhook,你也有个别的webhooks,它只触发特定的事件并产生比你在这里处理的JSON数据小得多的JSON数据。

I'd therefore advise you, to take a look in your Jira control panel (Or ask your Admin/Lead Dev/etc to take a look) and seriously trim down as much of that data as you can.

因此,我建议您查看您的Jira控制面板(或者请您的管理员/主管开发人员等查看)并尽可能地减少尽可能多的数据。

Further more, if memory serves me right, you can also make various web API calls to the Jira service to get this info too, and in that case you can tell the API exactly what your interested in, meaning it will only return the fields you need.

此外,如果内存对我有用,您也可以对Jira服务进行各种Web API调用以获取此信息,在这种情况下,您可以准确地告诉API您感兴趣的内容,这意味着它只会返回您的字段需要。

Right now, your main problem is the sheer volume of data your trying to deal with, if you tackle that problem, you'll find the issues surrounding the code your trying to get working will be very much easier to deal with.

现在,您的主要问题是您尝试处理的数据量庞大,如果您解决了这个问题,您会发现围绕您尝试工作的代码的问题将更容易处理。

Update 2

Just to make it clearer what I mean by using a "dynamic" type to get at your data, you would use something like the following code:

只是为了让我更清楚我的意思是使用“动态”类型来获取数据,你可以使用类似下面的代码:

string jsonString = "// Your json formated string data goes here";
var result = JsonConvert.DeserializeObject<dynamic>(jsonString);

The difference here is that your using the C# dynamic type rather than a strongly typed object of your own design.

这里的区别在于您使用C#动态类型而不是您自己设计的强类型对象。

"dynamic" is useful, because it's kind of like having an empty object, and then having the properties added for you, without you having to define it.

“dynamic”很有用,因为它有点像一个空对象,然后为你添加属性,而不必定义它。

What this essentially means is that, if you pass in the following JSON:

这实质上意味着,如果你传入以下JSON:

{'Name': 'A person', 'AllowAccess': true,'Areas': ['Sales','Admin']}

You'll end up with a dynamic object that looks like:

最终会得到一个动态对象,如下所示:

result = dynamic
{
  public string Name { get; set; }
  public bool AllowAccess { get; set; }
  public List<string> Areas { get; set; }
}

thus:

result.Name 

will get you access to the contents of the Name field and so on.

将让您访问“名称”字段的内容,依此类推。

If your JSON was then changed to become:

如果您的JSON随后更改为:

{'Name': 'A person', 'AllowAccess': true,'Areas': ['Sales','Admin'], 'Location': 'The World' }

Your object would magically have a property called 'Location' containing the value 'The World' which you could access using:

您的对象会神奇地拥有一个名为“位置”的属性,其中包含您可以使用以下权限访问的值“The World”:

result.Location

In your case, this would allow you to define your concrete object EG:

在您的情况下,这将允许您定义您的具体对象EG:

public MyObject
{
  public string Name { get; set; }
  public string Email { get; set; }
}

and then do something like the following (Assuming that your inbound JSON had properties in called Name & Email):

然后执行以下操作(假设您的入站JSON具有名为Name&Email的属性):

string jsonString = "// Your json formated string data goes here";
var result = JsonConvert.DeserializeObject<dynamic>(jsonString);
MyObject myObject = new MyObject
{
  Name = result.Name,
  Email = result.Email
}

You'd then discard the dynamic object as you'd not need it anymore.

然后,您将丢弃动态对象,因为您不再需要它了。

The BIG problem your going to have with this approach is maintaining your models. Manual property assignment is all fine and dandy for a small handful of properties and objects, but it soon becomes a huge maintenance nightmare as your software grows.

您将采用这种方法遇到的大问题是维护您的模型。手动属性分配对于少数几个属性和对象来说都很好,但是随着软件的增长,很快就会成为一个巨大的维护噩梦。

I'm sure it doesn't take much to imagine what kind of task you'd be facing if you had to do this for 100 different JSON requests and 50 different types of objects.

我敢肯定,如果您必须为100个不同的JSON请求和50种不同类型的对象执行此操作,那么您将面临什么样的任务并不需要太多。

For this reason, using this approach you should really consider using some kind of mapping technology such as "AutoMapper", however for now I'm going to advise you leave that until later before you start researching it, as it'll not help you to be clear about dealing with this dynamic approach.

出于这个原因,使用这种方法你应该考虑使用某种映射技术,如“AutoMapper”,但是现在我建议你把它留到你开始研究之前,因为它对你没有帮助明确处理这种动态方法。

#2


The JSON you get is already a string, so converting it to string doesn't make much sense. You need to create classes that reflect the structure represented by the JSON string.

你得到的JSON已经是一个字符串,所以将它转换为字符串没有多大意义。您需要创建反映JSON字符串表示的结构的类。

For example to convert the following JSON into objects, you'd have to create a class for the users:

例如,要将以下JSON转换为对象,您必须为用户创建一个类:

{"user":{"name":"asdf","teamname":"b","email":"c","players":["1","2"]}}

public class User
{
    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

Then you should be able to use this:

然后你应该能够使用这个:

JavaScriptSerializer jss= new JavaScriptSerializer(); 
List<User> users = jss.Deserialize<List<User>>(jsonResponse); 

#1


The easiest way to de-serialize Json in a C#/.NET program is to use the brilliant NewtonSoft JSON library.

在C#/ .NET程序中对Json进行反序列化的最简单方法是使用出色的NewtonSoft JSON库。

There are numerous ways to do it, but I have to admit that the NS libs just get on with the task (and no I'm not a member of the team etc, just an Avid User :-) ).

有很多方法可以做到这一点,但我不得不承认NS库只是继续执行任务(而且我不是团队的成员等,只是一个Avid用户:-))。

To do what you want for example, if you had:

要做你想做的事,例如,如果你有:

{'Name': 'A person', 'AllowAccess': true,'Areas': ['Sales','Admin']}

You would first build an object to represent it as follows:

您将首先构建一个对象来表示它,如下所示:

public MyObject
{
  public string Name { get; set; }
  public bool AllowAccess { get; set; }
  public List<string> Areas { get; set; }
}

Once you've done this, it's a simple case of just doing the following:

完成此操作后,只需执行以下操作即可:

string jsonString = "// Your json formated string data goes here";
MyObject myObject = JsonConvert.DeserializeObject<MyObject>(jsonString);

The properties in your object should at that point, reflect the properties in the JSON data you sent to it.

对象中的属性应该在此时反映您发送给它的JSON数据中的属性。

You will of course need to add the NS JSON Libs to your project, either via NuGet or Manually, which ever is easier for you, everything you need to know about that is here:

您当然需要通过NuGet或Manually将NS JSON Libs添加到您的项目中,这对您来说更容易,您需要了解的所有内容如下:

How to install JSON.NET using NuGet?

如何使用NuGet安装JSON.NET?

The really good thing about NS JSON however is not the ease of use, but the fact that it can also do dynamic de-serialization.

然而,NS JSON真正的好处不是易用性,而是它还可以进行动态反序列化。

This comes in handy if you've no idea what to expect in the JSON you receive, and so don't know ahead of time how to construct an object to hold the results.

如果你不知道你收到的JSON有什么期望,那么这就派上用场了,所以不要提前知道如何构造一个对象来保存结果。

Rather than repeat what others have said however, you can find more information of doing things dynamically in this stack overflow post:

然而,您可以在此堆栈溢出帖子中找到有关动态执行操作的更多信息,而不是重复其他人所说的内容:

Deserializing JSON using JSon.NET with dynamic data

使用带动态数据的JSon.NET反序列化JSON

Update

Looking at your JSON data you have way more fields/properties in there than your trying to parse, and none of the libraries in common use (To the best of my knowledge) will pick and choose the fields to copy, you either have an object that represents them all, or not at all, the later of which I believe is the problem your facing.

查看你的JSON数据,你有更多的字段/属性,而不是你想要解析的,并且没有一个常用的库(据我所知)将挑选并选择要复制的字段,你要么有一个对象这代表了他们所有人,或根本不代表他们,我认为这是你面临的问题。

I have a rather neat "JSON" plug in for chrome, than when given a chunk of JSON data formats the output for me nicely and makes it easy to read, it also helps massively when defining objects, allowing you to see the full nested structure of your data, here are a series of images showing your JSON data formatted using this plugin:

我有一个相当简洁的“JSON”插件用于chrome,比给我一大块JSON数据格式输出对我很好并且易于阅读,它也有助于大量定义对象,让你看到完整的嵌套结构您的数据,这里有一系列图像显示您使用此插件格式化的JSON数据:

将JSON数据转换为对象

将JSON数据转换为对象

I'm not going to paste anymore images in, but that goes on for another 4 pages!!

我不打算再粘贴图片了,但这还有4页!!

Now, some extra information that may help you.

现在,一些可能对您有帮助的额外信息。

I know from experience (I had to write a parser in PHP for these Jira webhooks) that within the Jira control panel, you can configure your webhooks to ONLY return the information your interested in.

我从经验中知道(我必须在PHP中为这些Jira webhooks编写一个解析器),在Jira控制面板中,您可以配置您的webhook只返回您感兴趣的信息。

Right now, it looks like you've just told the system to dump everything, for every event that you've hooked too (Which looks like - all of them), it's been a while since I did any work with these, but as well as a global webhook, you also have individual webhooks, which only fire on specific events and produce JSON data that's very much smaller than what your dealing with here.

现在,看起来你刚刚告诉系统转​​储所有内容,对于你所挂钩的每个事件(看起来都像 - 所有这些),已经有一段时间了,因为我做了这些工作,但是作为一个全球webhook,你也有个别的webhooks,它只触发特定的事件并产生比你在这里处理的JSON数据小得多的JSON数据。

I'd therefore advise you, to take a look in your Jira control panel (Or ask your Admin/Lead Dev/etc to take a look) and seriously trim down as much of that data as you can.

因此,我建议您查看您的Jira控制面板(或者请您的管理员/主管开发人员等查看)并尽可能地减少尽可能多的数据。

Further more, if memory serves me right, you can also make various web API calls to the Jira service to get this info too, and in that case you can tell the API exactly what your interested in, meaning it will only return the fields you need.

此外,如果内存对我有用,您也可以对Jira服务进行各种Web API调用以获取此信息,在这种情况下,您可以准确地告诉API您感兴趣的内容,这意味着它只会返回您的字段需要。

Right now, your main problem is the sheer volume of data your trying to deal with, if you tackle that problem, you'll find the issues surrounding the code your trying to get working will be very much easier to deal with.

现在,您的主要问题是您尝试处理的数据量庞大,如果您解决了这个问题,您会发现围绕您尝试工作的代码的问题将更容易处理。

Update 2

Just to make it clearer what I mean by using a "dynamic" type to get at your data, you would use something like the following code:

只是为了让我更清楚我的意思是使用“动态”类型来获取数据,你可以使用类似下面的代码:

string jsonString = "// Your json formated string data goes here";
var result = JsonConvert.DeserializeObject<dynamic>(jsonString);

The difference here is that your using the C# dynamic type rather than a strongly typed object of your own design.

这里的区别在于您使用C#动态类型而不是您自己设计的强类型对象。

"dynamic" is useful, because it's kind of like having an empty object, and then having the properties added for you, without you having to define it.

“dynamic”很有用,因为它有点像一个空对象,然后为你添加属性,而不必定义它。

What this essentially means is that, if you pass in the following JSON:

这实质上意味着,如果你传入以下JSON:

{'Name': 'A person', 'AllowAccess': true,'Areas': ['Sales','Admin']}

You'll end up with a dynamic object that looks like:

最终会得到一个动态对象,如下所示:

result = dynamic
{
  public string Name { get; set; }
  public bool AllowAccess { get; set; }
  public List<string> Areas { get; set; }
}

thus:

result.Name 

will get you access to the contents of the Name field and so on.

将让您访问“名称”字段的内容,依此类推。

If your JSON was then changed to become:

如果您的JSON随后更改为:

{'Name': 'A person', 'AllowAccess': true,'Areas': ['Sales','Admin'], 'Location': 'The World' }

Your object would magically have a property called 'Location' containing the value 'The World' which you could access using:

您的对象会神奇地拥有一个名为“位置”的属性,其中包含您可以使用以下权限访问的值“The World”:

result.Location

In your case, this would allow you to define your concrete object EG:

在您的情况下,这将允许您定义您的具体对象EG:

public MyObject
{
  public string Name { get; set; }
  public string Email { get; set; }
}

and then do something like the following (Assuming that your inbound JSON had properties in called Name & Email):

然后执行以下操作(假设您的入站JSON具有名为Name&Email的属性):

string jsonString = "// Your json formated string data goes here";
var result = JsonConvert.DeserializeObject<dynamic>(jsonString);
MyObject myObject = new MyObject
{
  Name = result.Name,
  Email = result.Email
}

You'd then discard the dynamic object as you'd not need it anymore.

然后,您将丢弃动态对象,因为您不再需要它了。

The BIG problem your going to have with this approach is maintaining your models. Manual property assignment is all fine and dandy for a small handful of properties and objects, but it soon becomes a huge maintenance nightmare as your software grows.

您将采用这种方法遇到的大问题是维护您的模型。手动属性分配对于少数几个属性和对象来说都很好,但是随着软件的增长,很快就会成为一个巨大的维护噩梦。

I'm sure it doesn't take much to imagine what kind of task you'd be facing if you had to do this for 100 different JSON requests and 50 different types of objects.

我敢肯定,如果您必须为100个不同的JSON请求和50种不同类型的对象执行此操作,那么您将面临什么样的任务并不需要太多。

For this reason, using this approach you should really consider using some kind of mapping technology such as "AutoMapper", however for now I'm going to advise you leave that until later before you start researching it, as it'll not help you to be clear about dealing with this dynamic approach.

出于这个原因,使用这种方法你应该考虑使用某种映射技术,如“AutoMapper”,但是现在我建议你把它留到你开始研究之前,因为它对你没有帮助明确处理这种动态方法。

#2


The JSON you get is already a string, so converting it to string doesn't make much sense. You need to create classes that reflect the structure represented by the JSON string.

你得到的JSON已经是一个字符串,所以将它转换为字符串没有多大意义。您需要创建反映JSON字符串表示的结构的类。

For example to convert the following JSON into objects, you'd have to create a class for the users:

例如,要将以下JSON转换为对象,您必须为用户创建一个类:

{"user":{"name":"asdf","teamname":"b","email":"c","players":["1","2"]}}

public class User
{
    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

Then you should be able to use this:

然后你应该能够使用这个:

JavaScriptSerializer jss= new JavaScriptSerializer(); 
List<User> users = jss.Deserialize<List<User>>(jsonResponse);