如何将JSON数据数组存储到C#集合中

huangapple go评论156阅读模式
英文:

How to store JSON array of data into C# collection

问题

var persons = JsonConvert.DeserializeObject<List<Member>>(AccountDetails);

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("InNumber", typeof(System.String)));
dt.Columns.Add(new DataColumn("OutNumber", typeof(System.String)));

foreach (var item in persons)
{
    DataRow dr = dt.NewRow();
    dr["InNumber"] = item.InNumber;
    dr["OutNumber"] = item.OutNumber;

    dt.Rows.Add(dr);
}
英文:

I have the below Json to my API - can you please suggest me how do I store these json data in to C# List or collection

{
  &quot;AccountDetails&quot;: [
    {
      &quot;InNumber&quot;: &quot;123453333&quot;,
      &quot;OutNumber&quot;: &quot;125666666&quot;
    },
    {
      &quot;InNumber&quot;: &quot;2345543334&quot;,
      &quot;OutNumber&quot;: &quot;4556666667&quot;
    },
    {
      &quot;InNumber&quot;: &quot;9793543333&quot;,
      &quot;OutNumber&quot;: &quot;2345543333&quot;
    }
  ]
}

I have tried below , but it snot working , kindly let me know if there is any better performance approach

var persons = JsonConvert.DeserializeObject&lt;List&lt;Member&gt;&gt;(AccountDetails);

    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn(&quot;InNumber&quot;, typeof(System.String)));
    dt.Columns.Add(new DataColumn(&quot;OutNumber&quot;, typeof(System.String)));
    

    foreach (var item in persons)
    {
        DataRow dr = dt.NewRow();
        dr[&quot;InNumber&quot;] = item.InNumber;
        dr[&quot;OutNumber&quot;] = item.OutNumber;

        dt.Rows.Add(dr);
    }

答案1

得分: 2

以下是代码部分的翻译:

这是对我的评论的详细说明。

这里我创建了一个类来保存您的帐户详细信息:

public class AccountDetail
{
    public string InNumber { get; set; }
    public string OutNumber { get; set; }
}

但是,您的JSON数据表示一个具有表示这些详细信息集合的单个属性的对象,所以我还需要这个:

public class Account
{
    public List<AccountDetail> AccountDetails { get; set; }
}

现在我可以将您的数据反序列化为一个Account实例:

public static void Test()
{
    const string data = @"
         {
          ""AccountDetails"": [
            {
                ""InNumber"": ""123453333"",
                ""OutNumber"": ""125666666""
            },
            {
                ""InNumber"": ""2345543334"",
                ""OutNumber"": ""4556666667""
            },
            {
                ""InNumber"": ""9793543333"",
                ""OutNumber"": ""2345543333""
            }
          ]
        }";
    var result = JsonConvert.DeserializeObject<Account>(data);
}

在回复我的评论中,您说:“我能够列出所有的InNumber和Outnumber,但很难确定哪个InNumber与Outnumber标记在一起 - 请问我该如何显示记录 - 以便很容易地识别两个相关的号码,因为最终我需要将InNumber和相应的Outnumber存储在数据库中。”

我不太明白。您有一个AccountDetail对象的列表,每个对象都有一个InNumber / OutNumber对。这很容易通过任何现代数据库访问机制(或者只需在INSERT语句周围循环)插入到数据库中。您没有显示您的数据库访问代码,所以我无法告诉您。

我可以告诉您的是,除非我正在处理非常古老的代码,否则我几乎不使用DataTable。

由于您似乎非常希望它在一个DataTable中,所以将以下代码添加到Test的末尾(在以var result =开头的行之后):

DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("InNumber", typeof(System.String)));
dataTable.Columns.Add(new DataColumn("OutNumber", typeof(System.String)));

foreach (var accountDetail in result.AccountDetails)
{
    DataRow dr = dataTable.NewRow();
    dr["InNumber"] = accountDetail.InNumber;
    dr["OutNumber"] = accountDetail.OutNumber;

    dataTable.Rows.Add(dr);
}
英文:

This is an elaboration of my comment.

Here I create a class to hold your account details:

public class AccountDetail
{
    public string InNumber { get; set; }
    public string OutNumber { get; set; }
}

But, your JSON data represents an object that has a single property that represents a collection of these, so I need this as well:

public class Account
{
    public List&lt;AccountDetail&gt; AccountDetails { get; set; }
}

Now I can deserialize your data into an Account instance:

public static void Test()
{
    const string data = @&quot;
         {
          &quot;&quot;AccountDetails&quot;&quot;: [
            {
                &quot;&quot;InNumber&quot;&quot;: &quot;&quot;123453333&quot;&quot;,
                &quot;&quot;OutNumber&quot;&quot;: &quot;&quot;125666666&quot;&quot;
            },
            {
                &quot;&quot;InNumber&quot;&quot;: &quot;&quot;2345543334&quot;&quot;,
                &quot;&quot;OutNumber&quot;&quot;: &quot;&quot;4556666667&quot;&quot;
            },
            {
                &quot;&quot;InNumber&quot;&quot;: &quot;&quot;9793543333&quot;&quot;,
                &quot;&quot;OutNumber&quot;&quot;: &quot;&quot;2345543333&quot;&quot;
            }
          ]
        }&quot;;
    var result = JsonConvert.DeserializeObject&lt;Account&gt;(data);
}

In a reply comment to my comment, you say " I am able to list the all inNumbers and outnumbers in a list but it's difficult to identify which is InNumber is tagged to Outnumber - can you please help me, how do I display records - such way that both the associated numbers can be easily identified , because at the end I need to to store InNumber and corresponding Outnumber in DB"

I'm not quite following. You have a list of AccountDetail objects, each of which has an InNumber / OutNumber pair. That's easily inserted into a database using any modern database access mechanism (or, just a loop around an INSERT statement). You don't show your database access code, so I can't tell you.

What I can tell you is that I nearly never use DataTables unless I'm working on really old code.

Since it appears you really want it in a DataTable, add this code to the end of Test (after the line that starts var result =):

DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn(&quot;InNumber&quot;, typeof(System.String)));
dataTable.Columns.Add(new DataColumn(&quot;OutNumber&quot;, typeof(System.String)));

foreach (var accountDetail in result.AccountDetails)
{
    DataRow dr = dataTable.NewRow();
    dr[&quot;InNumber&quot;] = accountDetail.InNumber;
    dr[&quot;OutNumber&quot;] = accountDetail.OutNumber;

    dataTable.Rows.Add(dr);
}

答案2

得分: 1

如果你想要一个 DataTable

DataTable dt = JObject.Parse(jsonString)["AccountDetails"].ToObject();


如果你想要一个 List

List persons = JObject.Parse(jsonString)["AccountDetails"].ToObject<List>();

public class AccountDetail
{
public string InNumber { get; set; }
public string OutNumber { get; set; }
}


<details>
<summary>英文:</summary>

if you want a DataTable 

DataTable dt = JObject.Parse(jsonString)["AccountDetails"].ToObject<DataTable>();

if you want a List

List<AccountDetail> persons = JObject.Parse(jsonString)["AccountDetails"].ToObject<List<AccountDetail>>();

public class AccountDetail
{
public string InNumber { get; set; }
public string OutNumber { get; set; }
}


</details>



# 答案3
**得分**: 1

你所展示的JSON是一个包含名为AccountDetails的属性的对象,其中包含了你的数组。请注意外部的JSON由{ }括起来,而不是[ ],这就是你看到那个错误的原因。

这是https://stackoverflow.com/questions/45066930/deserialize-json-into-c-sharp-collection的重复问题。

你可以像这样解决它:

[示例代码][1]

或者你可以从JSON对象中解析出集合(下面的答案)

创建一个包含AccountDetails列表的对象

```csharp
public class ListContainingObject
{
    public List<Member> AccountDetails;
}
```

将其反序列化为

```csharp
var listcontainingobject = JsonConvert.DeserializeObject<ListContainingObject>(jsontext);
```

[1]: https://dotnetfiddle.net/n15KRR

<details>
<summary>英文:</summary>

The JSON you&#39;ve shown is an Object with a Property called AccountDetails that contains your array. Note how the outer Json is surrounded by { } and not [ ] which is why you&#39;re seeing that error.

This is a duplicate of https://stackoverflow.com/questions/45066930/deserialize-json-into-c-sharp-collection

You could solve that, for instance, like this:

[working example][1]

or you parse the collection out of the JSON Object (the answer below)

Create an object that contains a list of AccountDetails

    public class ListContainingObject
    {
    	public List&lt;Member&gt; AccountDetails;
    }

deserialize to that 

    var listcontainingobject = JsonConvert.DeserializeObject&lt;ListContainingObject&gt;(jsontext);


https://dotnetfiddle.net/NXCrDC


  [1]: https://dotnetfiddle.net/n15KRR

</details>



huangapple
  • 本文由 发表于 2023年8月11日 04:47:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76879213.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定