如何在 ASP.NET Core 中的重复数据表值的 newsofton 中序列化 json

发布于 2025-01-11 16:30:25 字数 2287 浏览 0 评论 0原文

因此,我一直在尝试序列化我拥有的 json,以便从数据集中获得的定义值是我的 Json 数组中的“键”,并且如果有意义的话,所有值都在该键内。

我对此很陌生,我还没有找到任何其他帖子可以帮助我解决这个问题,所以希望你们中的一个人知道答案。

因此,我用来尝试实现此目的的代码如下:

string query = @"
                  select Country.Name, City.Name from world.country 
                  inner join world.city on world.country.Code = world.city.CountryCode
                  where CountryCode = @CountryCode";

  DataSet dataSet = new DataSet("dataSet");
  dataSet.Namespace = "NetFrameWork";
  DataTable table = new DataTable();
  dataSet.Tables.Add(table);

  string sqlDataSource = _configuration.GetConnectionString("WorldAppConnection");
  MySqlDataReader myReader;
  using (MySqlConnection mySqlConnection = new MySqlConnection(sqlDataSource))
  {
    mySqlConnection.Open();
    using (MySqlCommand mySqlCommand = new MySqlCommand(query, mySqlConnection))
    {
      mySqlCommand.Parameters.AddWithValue("@CountryCode", CountryCode);
      myReader = mySqlCommand.ExecuteReader();
      table.Load(myReader);
      myReader.Close();
      mySqlConnection.Close();
    }
  }
  dataSet.AcceptChanges();
  string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
  return json;
}

现在,如果我在 SQL 中执行此查询,结果会是一小段:

France |巴黎
法国 |马赛
法国 |里昂
法国 |图卢兹
...

现在这段代码生成的 Json 结果是:

{
  "Table1": [
    {
    "Name": "France",
      "Name1": "Paris"
    },
    {
    "Name": "France",
      "Name1": "Marseille"
    },
    {
    "Name": "France",
      "Name1": "Lyon"
    },
    {
    "Name": "France",
      "Name1": "Toulouse"
    },
    {
    "Name": "France",
      "Name1": "Nice"
    },
    {
    "Name": "France",
      "Name1": "Nantes"
    },
    {
    "Name": "France",
      "Name1": "Strasbourg"
    }
  ]
}   

正如您所看到的,它不断重复 France 字段。然而我想要的结果是这样的:

{
  "Table1": [ 
    {
     "France":[   
       {
         "Name1": "Paris"
       },
       {
         "Name1": "Marseille"
       },
       {
         "Name1": "Lyon"
       },
       {
         "Name1": "Toulouse"
       },
       {
         "Name1": "Nice"
       },
       {
         "Name1": "Nantes"
       },
       {
         "Name1": "Strasbourg"
       }
     ]
   }
 ]
}

有什么办法可以以任何方式实现这一目标吗?

提前致谢。

So I've been trying to serialize a json that I have so that the defining value I get from my dataset is a "key" in my Json array and that all the values are within that key if that makes sense.

I'm new to this and I haven't found any other post that would help me with this so hopefully one of you knows the answer.

So the code that I'm using to try and achieve this is as following:

string query = @"
                  select Country.Name, City.Name from world.country 
                  inner join world.city on world.country.Code = world.city.CountryCode
                  where CountryCode = @CountryCode";

  DataSet dataSet = new DataSet("dataSet");
  dataSet.Namespace = "NetFrameWork";
  DataTable table = new DataTable();
  dataSet.Tables.Add(table);

  string sqlDataSource = _configuration.GetConnectionString("WorldAppConnection");
  MySqlDataReader myReader;
  using (MySqlConnection mySqlConnection = new MySqlConnection(sqlDataSource))
  {
    mySqlConnection.Open();
    using (MySqlCommand mySqlCommand = new MySqlCommand(query, mySqlConnection))
    {
      mySqlCommand.Parameters.AddWithValue("@CountryCode", CountryCode);
      myReader = mySqlCommand.ExecuteReader();
      table.Load(myReader);
      myReader.Close();
      mySqlConnection.Close();
    }
  }
  dataSet.AcceptChanges();
  string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
  return json;
}

Now if I perform this query in SQL a small snippet of what the result is:

France | Paris
France | Marseille
France | Lyon
France | Toulouse
...

Now what this code results in as a Json is:

{
  "Table1": [
    {
    "Name": "France",
      "Name1": "Paris"
    },
    {
    "Name": "France",
      "Name1": "Marseille"
    },
    {
    "Name": "France",
      "Name1": "Lyon"
    },
    {
    "Name": "France",
      "Name1": "Toulouse"
    },
    {
    "Name": "France",
      "Name1": "Nice"
    },
    {
    "Name": "France",
      "Name1": "Nantes"
    },
    {
    "Name": "France",
      "Name1": "Strasbourg"
    }
  ]
}   

As you can see it keeps on repeating the France field. However the result I would want to have is something like:

{
  "Table1": [ 
    {
     "France":[   
       {
         "Name1": "Paris"
       },
       {
         "Name1": "Marseille"
       },
       {
         "Name1": "Lyon"
       },
       {
         "Name1": "Toulouse"
       },
       {
         "Name1": "Nice"
       },
       {
         "Name1": "Nantes"
       },
       {
         "Name1": "Strasbourg"
       }
     ]
   }
 ]
}

Is there any way to achieve this in any way?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

要走干脆点 2025-01-18 16:30:25

在序列化对象之前,可以使用 LINQ to DataSet 按Name属性对结果进行分组,请参考以下示例代码:

创建CountryViewModel类:

public class CountryViewModel
{
    public string Name1 { get; set; }
}

然后使用以下代码(我的应用程序名称是“Application1”,您可以将其更改为您的) :

//group the country by the name, 
var linqresult = dataSet.Tables[0].AsEnumerable()
                .GroupBy(c => c.Field<string>("Name"))
                .Select(c => new Dictionary<string, List<WebApplication1.Models.CountryViewModel>> {
                    {
                      (string)c.Key, 
                    c.Select(i => new WebApplication1.Models.CountryViewModel() { Name1 = (string)i["Name1"] }).ToList()
                    }}).ToList();
var newdic = new Dictionary<string, List<Dictionary<string, List<WebApplication1.Models.CountryViewModel>>>>();
newdic.Add("Table1", linqresult);
var linqjson = JsonConvert.SerializeObject(newdic, Formatting.Indented);

结果是这样的:

在此处输入图像描述

Before serialize the object, you can use LINQ to DataSet to group the result by the Name property, refer to the following sample code:

Create CountryViewModel class:

public class CountryViewModel
{
    public string Name1 { get; set; }
}

Then use the following code (My application name is "Application1", you can change it to yours):

//group the country by the name, 
var linqresult = dataSet.Tables[0].AsEnumerable()
                .GroupBy(c => c.Field<string>("Name"))
                .Select(c => new Dictionary<string, List<WebApplication1.Models.CountryViewModel>> {
                    {
                      (string)c.Key, 
                    c.Select(i => new WebApplication1.Models.CountryViewModel() { Name1 = (string)i["Name1"] }).ToList()
                    }}).ToList();
var newdic = new Dictionary<string, List<Dictionary<string, List<WebApplication1.Models.CountryViewModel>>>>();
newdic.Add("Table1", linqresult);
var linqjson = JsonConvert.SerializeObject(newdic, Formatting.Indented);

The result is like this:

enter image description here

尽揽少女心 2025-01-18 16:30:25

试试这个

dataSet.AcceptChanges();

//or this
string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
var jsonParsed = JObject.Parse(json); 

//or better 
var jsonParsed = JObject.FromObject(dataSet); 

var result = new
{
Table1 = jsonParsed["Table1"].GroupBy(x => x["Name"])
       .Select(x => new Dictionary<string, string[]> { { (string)x.Key, 
       x.Select(i => (string)i["Name1"]).ToArray() }})
};

结果

{
  "Table1": [
    {
      "France": [
        "Paris",
        "Marseille",
        "Lyon",
        "Toulouse",
        "Nice",
        "Nantes",
        "Strasbourg"
      ]
    }
  ]
}

try this

dataSet.AcceptChanges();

//or this
string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
var jsonParsed = JObject.Parse(json); 

//or better 
var jsonParsed = JObject.FromObject(dataSet); 

var result = new
{
Table1 = jsonParsed["Table1"].GroupBy(x => x["Name"])
       .Select(x => new Dictionary<string, string[]> { { (string)x.Key, 
       x.Select(i => (string)i["Name1"]).ToArray() }})
};

result

{
  "Table1": [
    {
      "France": [
        "Paris",
        "Marseille",
        "Lyon",
        "Toulouse",
        "Nice",
        "Nantes",
        "Strasbourg"
      ]
    }
  ]
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文