【问题标题】:C# how to write JSON with enumerated identifiersC#如何编写带有枚举标识符的JSON
【发布时间】:2021-08-02 17:50:12
【问题描述】:

我正在编写将 Excel 转换为 JSON 的代码(到目前为止它可以工作)。 但是我遇到了一个问题,我需要在单词 Match_ 之后对我写的每一行进行编号(又名 Match_1、Match_2、Match_3)。 如果您查看代码的末尾,我可能会尝试将 For?但它给了我所有的 Match_i.. 如何使用Replace 命令,以便在单词 Match_ 后面加上相应的数字?

IP = 我要添加到句子中的另一个字符串。忽略它

row[0] = 它从 excel 的行中提取的文本

Match_ 不是 var,它实际上是一个文本,我也可以在那里写 Oded_ 然后它会写 Oded_ = (IP string) + (excel text on row[0])

Match_ 是我实际上试图从文本中替换的文本,因为我无法在链接查询中执行 FOR。

using (var conn = new OleDbConnection(connectionString))
{
    conn.Open();

    var cmd = conn.CreateCommand();
    cmd.CommandText = $"SELECT * FROM [{sheetName}$]";

    using (var rdr = cmd.ExecuteReader())
    {
        if (rdr != null)
        {
            //LINQ query - when executed will create anonymous objects for each row
            var query = rdr.Cast<DbDataRecord>().Select(row => new
            {
                Match_ = IP + row[0]
            });


            //Generates JSON from the LINQ query
         
            var json = JsonConvert.SerializeObject(query);


        //Write the file to the destination path

        for (int i = 1; i<200; i++)
        {
            json = json.Replace("match_", "match_" + i );
        }
        File.WriteAllText(destinationPath, json);
    }
}

【问题讨论】:

  • 什么是Match_IP,它们在哪里定义?
  • IP 只是我添加到我从 Excel 中获取的行中的另一个字符串。 Match_ 取自 linkQuery 的位置(如果您看到 Match_ = IP + row[0]),当它转换为 Json 时,它会像文本上一样使用 Match_。
  • 使用 json 似乎是一件相当奇怪的事情。 Json 描述列表,但索引是隐式的。您确定像 CSV 这样的格式不会更适合您的用例吗?
  • 它适合我的工作,因为我需要将 Excel 转换为 Json 以提高工作效率,而不是手动完成。到目前为止一切正常,它转换了我需要的所有内容和所有文本,除了烦人的匹配,我需要以某种方式在它之后添加数字。到目前为止,它把它写下来。正确的文本=它正在做我需要它写的东西,我只是不能发布它抱歉:P Match_ =“正确的文本”Match_ =“正确的文本”,我需要它作为 Match_1 =“正确的文本”Match_2 =“正确的文本”

标签: c# json excel linq replace


【解决方案1】:

因此,在分配 query 之后,它是您的匿名类型的 IEnumerable&lt;&gt;,它将有 0 到多行。这些行实际上还没有被评估。需要记住的重要一点是,您正在创建匿名类型,而不是匿名对象,因此您的结果的所有枚举都必须是该类型,您不能一一切换。

有很多方法可以实现您想要的,但可能最方便的方法是将迭代器包含在您的选择枚举器中,然后返回 JObject 类似这样的东西,

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

...

var query = rdr.Cast<DbDataRecord>().Select((row, i) => {
    var result = new JObject();
    result.Add( $"match_{i}", IP + row[0]);
    return result;
});

那么您就不必对 JSON 进行任何容易出错且代价高昂的字符串操作,它已经被正确格式化了。

Here is a full working example of this in action,

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var query = Enumerable
            .Range(1,5)
            .Select( (n, i) =>
               {
                   var result = new JObject();
                   result.Add($"match_{i}", n);
                   return result;
               });
        
        Console.WriteLine(
            JsonConvert.SerializeObject(
                query, 
                Formatting.Indented));
    }
}

It is possible to do this with the more modern System.Text.Json but you'll have to embed the work in a writer.

【讨论】:

  • 嗨,我正在尝试这个,但我在“添加”时出错 JsonObject 不包含“添加”的定义
  • 对不起,我对编码还是有点陌生​​,现在我遇到了错误。 jsonvalue.pars 意外字符“h”。在第 1 行第 0 列。我相信它是因为 String IP = "texticantshow" (因为它以 h 开头,每次我更改它时,它都会说一个意想不到的字符,所以它与它有关)
  • @odedgross 我彻底检查了我的答案
  • 非常感谢,我会试试这个!
  • @odedgross,如果这有效或有帮助,您可以考虑在答案中注明。
【解决方案2】:

试试正则表达式。

    class Program
    {
        int i = 0;
        static void Main(string[] args)
        {
            string json = "match_   abc match_  def match_ hijmatch_";
            string pattern = "match_";

            Program p = new Program();
            MatchEvaluator myEvaluator = new MatchEvaluator(p.ReplaceCC);
            Regex r = new Regex(pattern);
            string output = r.Replace(json, myEvaluator);

        }
        public string ReplaceCC(Match m)
        // Replace each Regex cc match with the number of the occurrence.
        {
            i++;
            return m.Value + i.ToString();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多