错误的json数据发送到发布请求

时间:2017-08-31 07:35:44

标签: xamarin.android

你好我发送请求到服务器,我想使用newtonsoft

反序列化json字符串

我想发送这样的数据

    {

    "Id": 1,
    "PROF_EMAILD": "aaaa@gmail.com",
    "MAILID": "bbb@gmail.com",
    "NAME": "aaa"
}

我已经实现了this.code的一些代码,如下所示

 protected override string RunInBackground(params string[] @params)
    {
        string sUrl = "http://52.163.215.46:4444/api/FBLogins";
        string sContentType = "application/json"; // or application/xml
        try
        {
            JObject oJsonObject = new JObject();
            oJsonObject.Add("Id", 22);
            oJsonObject.Add("PROF_EMAILD", "aaa@gmail.com");

            oJsonObject.Add("MAILID", "aa@gmail.com");

            oJsonObject.Add("NAME", "aaa");


            HttpClient oHttpClient = new HttpClient();
            var oTaskPostAsync = oHttpClient.PostAsync(sUrl, new StringContent(oJsonObject.ToString(), Encoding.UTF8, sContentType));
            oTaskPostAsync.ContinueWith((oHttpResponseMessage) =>
            {
                Console.WriteLine("Abhijit", oHttpResponseMessage.ToString());
            });
        }
        catch (Java.Lang.Exception e)
        {

        }
        catch (System.Exception e)
        {

        }
        return null;

    }

但是发送请求时json看起来像这样

    {{

    "Id": 1,
    "PROF_EMAILD": "aaa@gmail.com",
    "MAILID": "aa@gmail.com",
    "NAME": "aaa"
}}//extra bracks

和我如何获得响应字符串以及如何在json中转换它

2 个答案:

答案 0 :(得分:0)

你可以尝试没有新的Sting Like。 var oTaskPostAsync = oHttpClient.PostAsync(sUrl,oJsonObject.ToString());

由于

答案 1 :(得分:0)

我认为最好的方法是做类似于newtonsoft文档页面上的示例https://www.newtonsoft.com/json/help/html/SerializingJSON.htm

创建要发送的数据模型:

public class Users
{
   public int Id {get; set;}
   public string PROF_EMAILD {get; set;}
   public string MAILID{get; set;}
   public string NAME{get; set;}
}

使用您的数据实例化该类:

Users user = new Users();
...ADD DATA TO USERS ...

using (var client = new HttpClient())
{
    var content = new StringContent(JsonConvert.SerializeObject(user));
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    var response = await client.PostAsync(new Uri("http://your-url"), content);

    /* handle response here*/
};

然后将'输出'发布到API