簡體   English   中英

使用 C# 將命名空間添加到動態 JSON 對象鍵

[英]Prepend namespace to dynamic JSON objects keys using C#

I have a business case where I need to take any incoming JSON payload (so the JSON object will have to be dynamic, not predefined by a C# class) and prepend a given namespace to all its containing keys.

例如,如果以下有效負載進入:

{
  "property1": "value1",
  "property2": 2,
  "property3": true,
  "property4": {
    "myArray": [
      {
        "arrayProperty1": "im the first object in array",
        "arrayProperty2": "some value"
      },
      {
        "arrayProperty1": "im the second object in array",
        "arrayProperty2": "some value"
      }
    ]
  }
}

那么它需要產生以下output:

{
  "mynamespace.property1": "value1",
  "mynamespace.property2": 2,
  "mynamespace.property3": true,
  "mynamespace.subObj": {
    "mynamespace.myArray": [
      {
        "mynamespace.arrayProperty1": "im the first object in array",
        "mynamespace.arrayProperty2": "some value"
      },
      {
        "mynamespace.arrayProperty1": "im the second object in array",
        "mynamespace.arrayProperty2": "some value"
      }
    ]
  }
}

這可以使用 C# 嗎? 我嘗試在 stackoverflow 上搜索任何類似的問題,但這是我得到的最接近的問題(他們正在使用 javascript): Prepending namespace to all of a JSON object's Keys

您可以使用 Json.Net 的LINQ-to-JSON API (JTokens) 創建一個簡短的輔助方法來完成此操作:

public static string AddPrefixToAllKeys(string json, string prefix)
{
    JContainer token = (JContainer)JToken.Parse(json);

    // Note: We need to process the descendants in reverse order here
    // to ensure we replace child properties before their respective parents
    foreach (JProperty prop in token.Descendants().OfType<JProperty>().Reverse().ToList())
    {
        prop.Replace(new JProperty(prefix + prop.Name, prop.Value));
    }
    
    return token.ToString();
}

然后像這樣使用它:

string modifiedJson = AddPrefixToAllKeys(originalJson, "mynamespace.");

工作演示: https://dotnetfiddle.net/AdkAO7

暫無
暫無

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

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