2017-02-23 13 views
0

我正在將branch.io請求複製到C#中,並試圖通過NewtonSoft再次序列化它們來創建URL。我很好地複製了URL創建請求的主要部分,它確實生成了一個URL。但是當我試圖在查詢中定義我的desktop_url和marketing_title時,我遇到了一個問題。

{"type":2, "branch_key":"key_test_lerbZ22zyjfpfFtl2auzukafywi220dN", "campaign":"new_product_annoucement", "channel":"email", "tags":["monday", "test123"], "data":"{\"name\": \"Alex\", \"email\": \"[email protected]\", \"user_id\": \"12346\", \"$desktop_url\": \"https://www.google.com\",\"$marketing_title\": \"This is Awesome\"}"} 

你可以從JSON查詢看到,桌面URL和營銷標題都具有在前面即$ DESKTOP_URL和$ marketing_title $符號。

我認爲這是阻礙我在C#中創建副本的問題。我知道查詢是正確的,就像現在運行它一樣,它肯定會鏈接到Google的搜索頁面。

我的C#代碼如下:

[HttpPost] 
    public string GetWithBody([FromBody] getInfo info) 
    { 
     String mesh = info.affCode + "=========>" + info.appType; 

     using (var client = new HttpClient()) 
     { 
      var request = new branchIOinfo() 
      { 
       type = 2, 
       branch_key = "key_test_lerbZ22zyjfpfFtl2auzukafywi220dN", 
       campaign = info.appType, 
       alias = info.affCode, 
       data = new BranchRequestData 
       { 
        desktop_url = "https://www.google.com/" 
       } 
      }; 

      var response = client.PostAsync("https://api.branch.io/v1/url", 
       new StringContent(JsonConvert.SerializeObject(request).ToString(), 
        Encoding.UTF8, "application/json")).Result; 

      if (response.IsSuccessStatusCode) 
      { 
       dynamic content = JsonConvert.DeserializeObject(
        response.Content.ReadAsStringAsync() 
        .Result); 

       return content.url; 
      } 
      else 
      { 
       return "Error Creating URL"; 
      } 

我的C#模型如下:

namespace BranchIOAPI.Models 
{ 
    public class getInfo 
    { 
    public string affCode { get; set; } 
    public string appType { get; set; } 
    } 

public class branchIOinfo 
{ 
    public int type { get; set; } 
    public string branch_key { get; set; } 
    public string campaign { get; set; } 
    public string alias { get; set; } 
    public BranchRequestData data { get; set; } 

} 

public class BranchRequestData 
{ 
    public string desktop_url { get; set; } 
} 
} 

我怎樣複製是$符號在此代碼或什麼是正確的方法複製該JSON查詢。

回答

2

雖然這提到分支,但問題是如何在使用C#時序列化期間更改屬性名稱。

我相信這裏的合適的方法是使用JsonPropertyAttribute:http://www.newtonsoft.com/json/help/html/JsonPropertyName.htm

所以在類的定義,你會做這樣的事情:

public class BranchRequestData 
{ 
    [JsonProperty("$desktop_url")] 
    public string desktop_url { get; set; } 
} 
0

亞歷克斯從這裏分行:

$開頭的參數只是在我們的系統中遺留約定。你可以像任何其他參數一樣指定它們,所以除非我忘記了C#的特別之處,否則只需使用$desktop_url$marketing_url作爲data對象內的鍵即可。

+1

嘿亞歷克斯,問題C#實際上並不承認$作爲可以附加到JSONString的字符。由於無法識別此前綴,它將返回一個錯誤。因此它必須像dwestgate所說的那樣完成。公共類BranchRequestData {0121}組; } } – Tyson