Search code examples
c#jsondictionaryjson.netjsonconvert

How to assign two new key values in a JObject from a dictionary?


Hi I have below method which I calling in and that generates two string value(Partition Key and Row key). and My json do not have these two keys, so I would like to add these two values in my existing Json.

I need help in modifying my code below to add these two keys and values:

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

Solution

  • You need to assign the result of GenerateKeys to a variable. Since GenerateKeys returns a tuple, you can simply reference each of the entries via Item1, Item2 etc, syntax, adding the properties to your 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"));
    }
    

    This results in the following JSON:

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