【问题标题】:How to assign two new key values in a JObject from a dictionary?如何从字典中分配 JObject 中的两个新键值?
【发布时间】:2021-09-01 06:18:57
【问题描述】:

嗨,我有下面的方法,我调用它并生成两个字符串值(分区键和行键)。而我的 json 没有这两个键,所以我想在我现有的 Json 中添加这两个值。

我需要帮助修改下面的代码以添加这两个键和值:

internal async Task<(string, string)> GenerateKeys( Dictionary<string, EntityProperty> arg )
{            
    var result = await GenerateValuesFromScript( arg, sbForKeyColumns );
    return (result.First().ToString(), result.Last().ToString());
}

var content = JsonConvert.DeserializeObject<JObject>( lines );
   
await GenerateKeys( jsonDictionary );// above method is called and two values are returned
content.Add( new JProperty( "PartitionKey", "//this is where I have to pass the above 1st values" ) );
content.Add( new JProperty( "RowKey", "//this is where I have to pass the above 2nd values" ) );

【问题讨论】:

    标签: c# json dictionary json.net jsonconvert


    【解决方案1】:

    您需要将GenerateKeys 的结果分配给一个变量。由于GenerateKeys 返回一个元组,您可以通过Item1Item2 简单地引用每个条目 等,语法,将属性添加到您的 JObject。

    var lines = "{\"id\": 1}";
    
    var content = JsonConvert.DeserializeObject<JObject>(lines);
    var keys = await GenerateKeys();// above method is called and two values are returned
    content.Add(new JProperty("PartitionKey", keys.Item1));
    content.Add(new JProperty("RowKey", keys.Item2));
        
    
    // This is a very simplistic example of your method since I can't reproduce your params
    internal async Task<(string, string)> GenerateKeys()
    {
        return await Task.FromResult(("PartitionKeyValue", "RowKeyValue"));
    }
    

    这会产生以下 JSON:

    {
      "id": 1,
      "PartitionKey": "PartitionKey",
      "RowKey": "RowKey"
    }
    

    【讨论】:

    • 行键像这样行键:[\r\n 0,\r\n 12,\r\n 0\r\n]XTTJF012.any way to fix this while 实际上值是[0,12,0]XTTF012
    • 你会在每个位置都有一致的类型吗?这只是添加回车数据,如果将每个数据点都视为字符串,则可以对其进行修剪。
    猜你喜欢
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多