简体   繁体   English

如何将 url-encoded 或 url-decoded 字符串转换为 json 格式,然后再转换为对象?

[英]How can I convert url-encoded or url-decoded string to json format and then to object?

I'm getting a post request to my api (x-www-form-urlencoded) and the body of the request looks like this:我收到了对我的 api (x-www-form-urlencoded) 的 post 请求,请求的正文如下所示:

worker=%7B%22_id%22%3A+%7B%22%24oid%22%3A+%2261asd23e9231241dfd2b4c3bd%22%7D%2C+%22sid%22%3A+%22WKb32df49cas43413585352e8a6e2%cd%22%22%%22%3A+1234154123%7D%7D&task=%7B%22_id%22%3A+%7B%22%24oid%22%3A+%2261caffc34dsf33182b4c789

continues.继续。 There are 2 objects (classes) that I need to receive in this incoming request, and I created the class structure of these 2 objects: For example, my class structure is as follows:在这个传入的请求中我需要接收2个对象(类),我创建了这2个对象的类结构: 比如我的类结构如下:

public class Worker
{
    [JsonProperty("friendly_name")]
    public string FriendlyName { get; set; }

    [JsonProperty("date_updated")]
    public WorkerDateUpdated DateUpdated { get; set; }

    [JsonProperty("activity")]
    public string Activity { get; set; }

    [JsonProperty("workspace_sid")]
    public string WorkspaceSid { get; set; }

    [JsonProperty("date_created")]
    public WorkerDateCreated DateCreated { get; set; }

    [JsonProperty("queues")]
    public List<string> queues { get; set; }
 }

public class Task
{
    [JsonProperty("reason")]
    public string Reason { get; set; }

    [JsonProperty("date_updated")]
    public TaskDateUpdated DateUpdated { get; }

    [JsonProperty("assignment_status")]
    public string AssignmentStatus { get; set; }

    [JsonProperty("total_cost")]
    public TaskTotalCost TotalCost { get; set; }
}

In the incoming request, I receive 3 objects (class) as url-encoded, I only need 2 objects and their properties.在传入的请求中,我收到 3 个对象(类)作为 url 编码,我只需要 2 个对象及其属性。

 using (var reader = new StreamReader(
                                              HttpContext.Request.Body,
                                              encoding: Encoding.UTF8,
                                              detectEncodingFromByteOrderMarks: false
                                       ))
            {
                var bodyString = await reader.ReadToEndAsync();

                _logger.LogInformation("BodyString ---> " + bodyString);

                var decodedUrl = HttpUtility.UrlDecode(bodyString);
               _logger.LogInformation(" decodedUrl ---> " + decodedUrl);
}

I can read the incoming body and convert it to decoded format.我可以读取传入的正文并将其转换为解码格式。 Below is an example:下面是一个例子:

   worker={"_id": {"$oid": "XXXXXXXXXX"}, "sid": "XXXXXXXXXXXXX", "x": true, "account_sid": "XXXXXXXXXXXX", "workspace_sid": "XXXXXXXXXXXX", "queues ": ["XXXXXXXXXXXXXX"], "activity": "idle", "available": true, "friendly_name": "XXXXXXXX", "attributes": {"mail": "XXXXXXXXXXXX", "name": "XXXXXXXXXX" }, "date_created": {"$date": XXXXXXXXX}, "date_updated": {"$date": XXXXXXXXXX}, "date_status_changed": {"$date": XXXXXXXXXXXXX}}&task={"_id": {" $oid": "XXXXXXXXXXXXXX"}, "sid": "XXXXXXXXXXXX", "x": true, "account_sid": "XXXXXXXXXXX", "workspace_sid": "XXXXXXXXXXXXXXXXXX", "workflow_sid": "XXXXXXXXXXXX", "workflow_friendly_name" : "daytime1", "initial_attributes": {"station_name": "XXXXX", "component_type": X, "component_id": XXX, "mail": "XXXXXX", "main_issue": "XXXXXXXXXXXXXX", "predictivi_maintenance_time": "XXXXXXXXXX", "hospital_name": "\u00dcsk\u00fcdar XXXXXXXXXXX"}

I can see it as , but I can't deserialize it.我可以将其视为 ,但无法反序列化它。 Or I don't know if I'm doing it wrong.或者我不知道我是否做错了。 I have created a separate class that contains my 2 classes.我创建了一个单独的类,其中包含我的 2 个类。 I keep my Worker and Task class in it, I cannot deserialize to that class, it does not deserialize in any way.我将我的 Worker 和 Task 类保留在其中,我无法反序列化为该类,它不会以任何方式反序列化。 Unexpected charachter throws exception.意外的字符引发异常。 How can I convert these objects to json format or object format?如何将这些对象转换为 json 格式或对象格式?

Edit: My Other Custom classes:编辑:我的其他自定义类:

public class TaskDateUpdated
{
    [JsonProperty("$date")]
    public long Date { get; set; }
}
public class TaskTotalCost
{
    [JsonProperty("$numberDecimal")]
    public string NumberDecimal { get; set; }
}

public class TaskDateCreated
{
    [JsonProperty("$date")]
    public long Date { get; set; }
}

public class TaskLastChargeDate
{
    [JsonProperty("$date")]
    public long Date { get; set; }
}
public class TaskId
{
    [JsonProperty("$oid")]
    public string Oid { get; set; }
}

 public class WorkerDateUpdated
{
    [JsonProperty("$date")]
    public long date { get; set; }
}

public class WorkerDateCreated
{
    [JsonProperty("$date")]
    public long date { get; set; }
}

public class WorkerDateStatusChanged
{
    [JsonProperty("$date")]
    public long date { get; set; }
}

I also have a single class containing these 2 classes, I get an error when I try to deserialize to this class, I also get an error when I try to deserialize it to other worker and task classes separately.我还有一个包含这两个类的类,当我尝试反序列化到这个类时出现错误,当我尝试将它分别反序列化到其他工作类和任务类时也会出现错误。 I can't deserialize at all.我根本无法反序列化。

public class DataContainer
{
    public Task Task { get; set; }
    public Worker Worker { get; set; }
}

My post method looks like this:我的 post 方法如下所示:

     [HttpPost]
     [Consumes("application/x-www-form-urlencoded")]
     public async Task<ActionResult<ResponseRequest>> AddWorkerTask()
    {
      using (var reader = new StreamReader(
                                           HttpContext.Request.Body,
                                           encoding: Encoding.UTF8,
                                              detectEncodingFromByteOrderMarks: false
                                       ))
            {
                var bodyString = await reader.ReadToEndAsync();

                _logger.LogInformation("BodyString ---> " + bodyString);

                var decoded = HttpUtility.UrlDecode(bodyString);

                //here is where i need to deserialize and convert it to 
                //a valid json and object
            }
    }

You can use HttpUtility.ParseQueryString to parse it into a NameValueCollection , then simply use the indexer ["worker"] on that.您可以使用HttpUtility.ParseQueryString将其解析为NameValueCollection ,然后简单地使用索引器["worker"]

 [HttpPost]
 [Consumes("application/x-www-form-urlencoded")]
 public async Task<ActionResult<ResponseRequest>> AddWorkerTask()
 {
     using (var reader = new StreamReader(
                                        HttpContext.Request.Body,
                                        encoding: Encoding.UTF8,
                                           detectEncodingFromByteOrderMarks: false
                                    ))
     {
         var bodyString = await reader.ReadToEndAsync();
         var decoded = HttpUtility.ParseQueryString(bodyString);
         var worker = JsonSerializer.Deserialize<Worker>(decoded["worker"]);
         var task = JsonSerializer.Deserialize<Task>(decoded["task"]);
                          // or whatever your JSON deserializer is
     }
 }

In newer versions of ASP.net Core you can use HttpContext.Request.Form在较新版本的 ASP.net Core 中,您可以使用HttpContext.Request.Form

 [HttpPost]
 [Consumes("application/x-www-form-urlencoded")]
 public async Task<ActionResult<ResponseRequest>> AddWorkerTask()
 {
     var worker = JsonSerializer.Deserialize<Worker>(HttpContext.Request.Form["worker"]);
     var task = JsonSerializer.Deserialize<Task>(HttpContext.Request.Form["task"]);        // or whatever your JSON deserializer is
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM