簡體   English   中英

C# 如何用枚舉標識符編寫 JSON

[英]C# how to write JSON with enumerated identifiers

我正在編寫一個代碼來將 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);
    }
}

因此,在分配query之后,查詢是您的匿名類型的IEnumerable<> ,它將有 0 到多行。 這些行實際上還沒有被評估。 需要記住的重要一點是,你是在做一個匿名類型,而不是匿名 object,所以你的結果的所有枚舉都必須是那個類型,你不能一一切換。

有很多方法可以實現您想要的,但可能最方便的方法是將迭代器包含在您的 select 枚舉器中,然后返回類似這樣的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 進行任何容易出錯且代價高昂的字符串操作,它已經被正確格式化。

這是一個完整的工作示例

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));
    }
}

可以使用更現代的 System.Text.Json 來執行此操作,但您必須將工作嵌入到編寫器中。

嘗試正則表達式。

    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();
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM