将Json转换成Poco Collection/如何为For每个编写代码? [英] Convert Json to Poco Collection/ How to code a For Each?

查看:79
本文介绍了将Json转换成Poco Collection/如何为For每个编写代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Azure Functions还是很陌生.

I'm fairly new to Azure Functions.

我创建了一个C#WebHook/Azure函数(我想这是对的),以获取json内容并将其转换为简单的poco/dto对象的集合.

I've created a C# WebHook / Azure Function (I guess that's the right thing) to take my json content and convert it into a collection of simple poco/dto objects.

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

            //IUnityContainer container = new UnityContainer();
            //container.RegisterType<IJsonToPersonRequestWrapperConverter, JsonToPersonRequestWrapperConverter>();
            //IJsonToPersonRequestWrapperConverter jsonConvtr = container.Resolve<IJsonToPersonRequestWrapperConverter>();
            //ICollection<Person> emps = await jsonConvtr.ConvertHttpRequestMessageToPersonCollection(req);

            /* above commented code is my "real" code where I  take the INPUT request-body-as-json and convert it into a ICollection of Person(s) */
            /* 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< 10; i++)
            {
                persons.Add(new Person() { PersonUuid = Guid.NewGuid(), LastName = "LN" + i.ToString(), FirstName = "FN" + i.ToString(), BirthDate = DateTimeOffset.Now.AddYears(-1 * (20 + i))});
            }

            string serializedJson = Newtonsoft.Json.JsonConvert.SerializeObject(persons);

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

            return req.CreateResponse(HttpStatusCode.OK , serializedJson);

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

在另一个.cs文件中

public class Person
{

    public Guid PersonUuid { get; set; }

    public string LastName { get; set; }

    public string FirstName { get; set; }

    public DateTimeOffset? BirthDate { get; set; }
}

如果我在Visual Studio中调试它,则可以正常工作.

If I debug it in Visual Studio, it works fine.

因此我将其添加为逻辑应用程序的一个步骤,如下所示

So I added this as a step on my Logic App as seen below

因此,我想添加一个新步骤,即针对每个步骤".这是我现在得到的:(下图).我看到的只是初始触发器中的"body"和转换" webhook函数(我在上面有)……..

So I want to add a new step that is a "for each" step. Here is what I get now: (image below). All I see is "body" from the initial trigger and the "convert" webhook function (that I have above)........

如何显示人员"(以便我可以按每个人做)集合,并显示在Logic App上的下一步?

How do I get the "persons" (so I can do a for-each-person) collection to show up and be available for the next step on the Logic App?

EDIT/APPEND:

EDIT/APPEND:

最终的结果是为每个"人推送服务总线消息.

The end game is to push a service-bus-message for "each" of my Person(s).

根据要求,这里是人json" .....

As requested, here is the "person json".....

[{
    "PersonUuid": "7ec8cc4d-831c-4c89-8516-47424ee2658d",
    "LastName": "LN0",
    "FirstName": "FN0",
    "BirthDate": "1997-08-17T09:46:16.9839382-04:00"
},
{
    "PersonUuid": "275264bc-5a86-476d-a189-512afa1e3ce4",
    "LastName": "LN1",
    "FirstName": "FN1",
    "BirthDate": "1996-08-17T09:46:16.9844385-04:00"
},
{
    "PersonUuid": "e522b827-2d2e-465d-a30a-c4b619d2e8e4",
    "LastName": "LN2",
    "FirstName": "FN2",
    "BirthDate": "1995-08-17T09:46:16.9844385-04:00"
},
{
    "PersonUuid": "f16bce36-3491-4519-bc82-580939f61b2e",
    "LastName": "LN3",
    "FirstName": "FN3",
    "BirthDate": "1994-08-17T09:46:16.9844385-04:00"
},
{
    "PersonUuid": "42456057-39ef-45aa-bd7c-ad6a8fa74fd1",
    "LastName": "LN4",
    "FirstName": "FN4",
    "BirthDate": "1993-08-17T09:46:16.9844385-04:00"
},
{
    "PersonUuid": "14088a6e-3c44-4cb0-927d-19f5eda279c4",
    "LastName": "LN5",
    "FirstName": "FN5",
    "BirthDate": "1992-08-17T09:46:16.9844385-04:00"
},
{
    "PersonUuid": "332a5cde-3cd1-467a-9dfc-2b187d6ae32e",
    "LastName": "LN6",
    "FirstName": "FN6",
    "BirthDate": "1991-08-17T09:46:16.9844385-04:00"
},
{
    "PersonUuid": "6debe134-19e6-4b16-a91d-05ded511eff6",
    "LastName": "LN7",
    "FirstName": "FN7",
    "BirthDate": "1990-08-17T09:46:16.9844385-04:00"
},
{
    "PersonUuid": "e61ef8a1-09d3-4c5b-b948-df8e0858cd29",
    "LastName": "LN8",
    "FirstName": "FN8",
    "BirthDate": "1989-08-17T09:46:16.9844385-04:00"
},
{
    "PersonUuid": "e9b27632-d3a4-4fe8-8745-04edfa8854f7",
    "LastName": "LN9",
    "FirstName": "FN9",
    "BirthDate": "1988-08-17T09:46:16.9844385-04:00"
}]

推荐答案

确定.

在忘记之前,我必须记下来.哇,太好了.

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

首先在WebHook上使用C#代码.请注意"anonymousPersonWrapper"代码.

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

但是在"return returnReq;"上设置一个断点,我能够看到personWrapperJsonString包含下面的Json:

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"
    }]
}

好的.

然后我添加了一个解析Json"操作(如下图所示)

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

然后,我设置了Parse-Json.在下面.

Then I setup the Parse-Json. Below.

上面的parse-json设置未完成.

The above parse-json setup is not complete.

单击使用示例有效负载来生成模式"按钮,这将弹出一个新窗口.从先前粘贴到您的"personWrapper" json中.如下图所示.

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.

以上内容当然会创建您需要的json模式(对每个用户都是友好的).如下所示.

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

现在我们很亲近.

添加每次访问(添加新步骤时使用更多"按钮)(如下所示)

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

现在,我们为每个设置.看着出现了什么! "personWrapper"(下图)

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

对于咧嘴笑,我将sessionId设为PersonUuid值(只是为了表明我可以掌握该对象的标量属性之一.(下图).

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).

现在将json作为服务总线消息的内容. (下图)

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

然后我发布了Azure功能并部署了Logic-App,并向触发器发送了一个请求.

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

返回天蓝色门户. PersonUuid显示为SessionId! (下图)

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

然后快速检查Service Bus Explorer以窥视"消息的内容(下图)

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

好,有几个面包屑:

我从这里得到了一个提示,关于将收藏方放在包装纸"上.

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

Json.NET针对Schema验证JSON数组

我遇到的一些错误

无效的类型.期望的对象但是得到了数组."

"Invalid type. Expected Object but got Array."

UnsupportedMediaType"WebHook请求必须包含格式为JSON的实体主体."

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

此输出是一个数组"一个foreach不能嵌套在另一个foreach中"

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

'Json'期望其参数为字符串或XML.所提供的值为'Array'类型.

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

这篇关于将Json转换成Poco Collection/如何为For每个编写代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆