如何使用c#将另外一个属性添加到Azure Functions中的现有json对象中? [重复]

问题描述 投票:0回答:1

Azure function里面我的input is ServiceBus queue properties

代码是检索所有属性是 -

using System.Net;
using Newtonsoft.Json;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{

 string jsonContent = await req.Content.ReadAsStringAsync();

    return req.CreateResponse(HttpStatusCode.OK,jsonContent);
}

输出是 -

[
    "{\"DeliveryCount\":\"1\",\MessageId\":\"bac52de2d23a487a9ed388f7313d93e5\"}"
]

我想在这个json对象中再添加一个属性,如何在azure函数中添加它,以便我可以像下面一样返回修改后的对象 -

[
    "{\"DeliveryCount\":\"1\",\MessageId\":\"bac52de2d23a487a9ed388f7313d93e5\",\"MyProperty\":\"TEST\"}"
]
c# json azure azure-functions
1个回答
1
投票

我认为你可以很容易地做到这一点,通过将JSON反序列化到一个对象,添加你的新属性,然后再将它序列化。你甚至不需要具体的类型 - dynamic应该为你做的工作。

例如:

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    string jsonContent = await req.Content.ReadAsStringAsync();
    dynamic obj = JsonConvert.DeserializeObject<dynamic>(jsonContent);
    obj.MyProperty = "TEST";
    string extendedJSON = JsonConvert.SerializeObject(obj);
    return req.CreateResponse(HttpStatusCode.OK, extendedJSON);
}
© www.soinside.com 2019 - 2024. All rights reserved.