簡體   English   中英

Web API和應用程序/ x-www-form-urlencoded JSON

[英]Web API and application/x-www-form-urlencoded JSON

我正在研究從第三方來源接收數據的網絡掛鈎。 不幸的是,他們以非常奇怪和不正當的方式向我發布數據。 盡管如此,這是我必須處理的。 他們正在以以下格式發送內容類型為application/x-www-form-urlencoded的數據:

randomJsonObjects: 
[
  {
    "email": "john@example.com",
    "timestamp": 1337197600,
    "id": "55555",
  },
  {
    "email": "johnny@example.com",
    "timestamp": 1337547600,
    "id": "44444",
  }
]

當然,這不是有效的JSON,但也不是這樣發送的。 我的問題是我無法獲取Web API來正確解析它。 通常使用JSON時,我將其用作控制器:

public HttpResponseMessage Create(List<MyObject> jsonObjects)

但這是行不通的。 我嘗試了許多選項,但總是以空值結尾。

您必須使用newtonsoft.json

能夠反序列化匿名對象,幾乎所有json內容都可以檢出: http : //json.codeplex.com/

對於您而言,我認為像這樣的簡單代碼就可以解決問題:

List<dynamic> randomJsonObjects= JsonConvert.DeserializeObject<List<dynamic>>(randomJsonObjects);

問題是您的代碼以randomJsonObjects開頭:因此您只需刪除它,然后在上面的行中調用即可。 或添加{}將其轉換為對象

application/x-www-form-urlencoded編碼的數據結構與NameValueCollection非常相似。

捕獲查詢字符串,然后嘗試使用HttpUtility.ParseQueryString對其進行解析 此外, 此SO可能會有所幫助

嘗試查看以下內容是否滿足您的需求...在此,我做出一個很大的假設,即請求內容的格式始終像randomJsonObjects:[.....] ,因此我嘗試首先進行分析以了解其內容有效的json,如果沒有,我要添加一個環繞{}字符。

當然,可以改進此方法,以便您始終專門處理某些類型的參數(例如,本例中為AddressBook ),因此您可能希望將以下邏輯寫入諸如HttpParameterBinding的情況中,無論在哪種情況下在操作上使用此參數,以下解決方法將被使用...

public async Task Post()
{
    bool validJson = false;
    string originalData = await Request.Content.ReadAsStringAsync();

    try
    {
        JObject jo = JObject.Parse(originalData);
        validJson = true;
    }
    catch (JsonReaderException)
    {
    }

    string modifiedData = null;
    if (!validJson)
    {
        modifiedData = "{" + originalData + "}";
    }
    else
    {
        modifiedData = originalData;
    }

    AddressBook book = JsonConvert.DeserializeObject<AddressBook>(modifiedData);

    //TODO: do something with the book
}

public class AddressBook
{
    [JsonProperty("randomJsonObjects")]
    public IEnumerable<ContactInfo> Contacts { get; set; }
}

public class ContactInfo
{
    public string Email { get; set; }
    public long TimeStamp { get; set; }
    public string Id { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM