Convert Json to Poco Collection/ How to code a For Each?

不问归期 提交于 2019-12-06 08:16:14

Ok.

I gotta get this written down before I forget. Wow, what a ride.

First the C# code on the WebHook. Note the "anonymousPersonWrapper" code.

public static class GenericWebHookCSharp
{
    [FunctionName("GenericWebHookCsharpOne")]
    public static async Task<HttpResponseMessage /* object */> Run([HttpTrigger(WebHookType = "genericJson")]HttpRequestMessage req, TraceWriter log)
    {
        try
        {

            log.Info(string.Format("C# GenericWebHookCsharpOne about to process a request. ('{0}')", DateTime.Now.ToLongTimeString()));

            ///////* below code, I just fake-creating some persons */
            string jsonContent = await req.Content.ReadAsStringAsync();
            ICollection<Person> persons = new List<Person>();
            for (int i = 0; i < 3; i++)
            {
                persons.Add(new Person() { PersonUuid = Guid.NewGuid(), LastName = "LN" + i.ToString(), FirstName = "FN" + i.ToString(), BirthDate = DateTimeOffset.Now.AddYears(-1 * (20 + i)) });
            }

            /* the below is the "trick" to allow the for-each to work in the Logic-App.  at least in my experience */
            var anonymousPersonWrapper = new
            {
                personWrapper = persons
            };

            string personWrapperJsonString = JsonConvert.SerializeObject(anonymousPersonWrapper);

            log.Info(string.Format("C# GenericWebHookCsharpOne finished a request. ('{0}')", DateTime.Now.ToLongTimeString()));
            HttpResponseMessage returnReq = req.CreateResponse(HttpStatusCode.OK , personWrapperJsonString );
            return returnReq;

        }
        catch (Exception ex)
        {
            string errorMsg = ex.Message;
            log.Error(errorMsg);
            return req.CreateResponse(HttpStatusCode.BadRequest, errorMsg);
        }
    }
}

But putting a breakpoint on "return returnReq;", I was able to see that personWrapperJsonString contained the below Json:

{
    "personWrapper": [{
        "PersonUuid": "31fb318d-a9bf-4c2f-ad16-0810ddd73746",
        "LastName": "LN0",
        "FirstName": "FN0",
        "BirthDate": "1997-08-17T15:10:08.9633612-04:00"
    },
    {
        "PersonUuid": "73fdacc7-e1e8-48ff-b161-1bd8b5f4aec1",
        "LastName": "LN1",
        "FirstName": "FN1",
        "BirthDate": "1996-08-17T15:10:08.9633612-04:00"
    },
    {
        "PersonUuid": "d18b4324-2d3e-41ca-9525-fe769af89e9c",
        "LastName": "LN2",
        "FirstName": "FN2",
        "BirthDate": "1995-08-17T15:10:08.9633612-04:00"
    }]
}

Ok.

Then I added a "Parse Json" action (below image)

Then I setup the Parse-Json. Below.

The above parse-json setup is not complete.

Click on the button "Use sample payload to generate schema" and that will pop a new window. Paste in your "personWrapper" json from earlier. As seen in the below image.

The above will of course create the json-schema that you need (that is for-each friendly). As seen below.

Now we're so close.

Add a For-Each (using the "More" button when you add a new step) (as seen below)

Now we setup the for-each. Looked what showed up! The "personWrapper" (below image)

For grins, I made the sessionId be the PersonUuid value (just to show that I can get hold of one of the scalar properties of the object. (image below).

And now the json as the Content of the Service Bus message. (below image)

I then published the Azure-Functions and deployed the Logic-App, and sent a request to the trigger.

Back to azure portal. The PersonUuid showed up as the SessionId! (image below)

And a quick check in Service Bus Explorer to "peek" the contents of the message (image below)

Ok, a few breadcrumbs:

I got a hint from here about putting the collection side a "wrapper".

Json.NET validate JSON array against Schema

A few errors I got along the way

"Invalid type. Expected Object but got Array."

UnsupportedMediaType "The WebHook request must contain an entity body formatted as JSON."

"this output is an array" "a foreach cannot be nested inside of another foreach"

'Json' expects its parameter to be a string or an XML.The provided value is of type 'Array.

As Steven Van Eycken mentioned that we could parse string to array with json fucntion in the logic application. In your case we could parse the string to array in the Logic app or return jarry directly from Azure function . We can choose one of the following ways to do that . I also test it on my side, it works correctly.

In the logic App

json(body('Your action name'))

Or

Return Jarry directly in the Azure function

var jarry =JArray.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(persons));

log.Info(string.Format("C# GenericWebHookCsharpOne finished a request. ('{0}')", DateTime.Now.ToLongTimeString()));

return req.CreateResponse(HttpStatusCode.OK, jarry);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!