0

Inside the Azure function my input is ServiceBus queue properties

Code is to retrieve that all properties are -

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

Output is -

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

I want to add one more property into this json object , how can I add it here in azure function so that I can return modified object like below -

[
    "{\"DeliveryCount\":\"1\",\MessageId\":\"bac52de2d23a487a9ed388f7313d93e5\",\"MyProperty\":\"TEST\"}"
]
7
  • serialise it to a type, add your property and deserialise again? Commented Jan 3, 2018 at 10:52
  • I dont have any type because i'm doing it into Azure Functions dynamically. Commented Jan 3, 2018 at 10:53
  • 1
    you could deserialise to dynamic. Doesn't have to be a concrete type. Commented Jan 3, 2018 at 10:54
  • 1
    dynamic x = JsonConvert.DeserializeObject<dynamic>(jsonContent); I would have thought. Then you can add a new property, and serialize it back again before returning it. Commented Jan 3, 2018 at 11:01
  • 1
    x.NewProperty = "y". That's the whole point about dynamic, it's, well...dynamic. Commented Jan 3, 2018 at 11:04

1 Answer 1

1

I think you can do this quite easily, by de-serialising the JSON to an object, adding your new property and then serialising it back again. You don't even need a concrete type for this - dynamic should do the job for you.

For example:

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.