在C#

时间:2015-08-04 22:44:58

标签: c# json rest

我试图将JSON数据发送到REST服务但是收到错误。 JSON数据为{"Project":111,"itemType":123,"fields":{"name":"Test","Description":"Tseting only"}}

以下是代码

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//I'm passing the url from as a parameter
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("xxxx:xxxx"));
request.ContentType = "text/json";
request.Method = "POST";
//string names = "praneeth";
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
    string json =
        "{ \"project\": 111," +
        "\"itemType\": 123," +
        "\"fields\":\"{ \"name\":\"Test\"," + "\"description\":\"Testing only\"}\"}";
    streamWriter.Write(json);
}
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader sreader = new StreamReader(dataStream);
string responsereader = sreader.ReadToEnd();
response.Close();

我得到的错误是

  

{"元" {"状态":"差   请求","时间戳":" 2015-08-04T22:40:55.645 + 0000","消息":"不能   从String值实例化java.util.LinkedHashMap类型的值   (' {');没有单字符串构造函数/工厂方法\ n在[来源:   org.glassfish.jersey.message.internal.EntityInputStream@50e3274b;   line:1,column:33](通过参考链:   com.jamasoftware.contour.rest.v1.domain.RequestItem [\"字段\"])"}}

2 个答案:

答案 0 :(得分:0)

你说JSON数据是这样的:

{"Project":111,"itemType":123,"fields":{"name":"Test","Description":"Tseting only"}}

但你实际构建的是:

{ "project": 111,"itemType": 123,"fields":"{ "name":"Test","description":"Testing only"}"}

哪个是无效的JSON。

所以,删除那些额外的引号。

答案 1 :(得分:-1)

您当前正在将fields作为字符串发送,该字符串对该属性的目标类型无效。取出封装的引号,改为发送一个对象。

如下:

 string json =
      "{"
       + "\"project\": 111,"
       + "\"itemType\": 123,"
       + "\"fields\": { "
           + "\"name\" : \"Test\","
           + "\"description\":\"Testing only\""
       + "}" +
       "}";
 streamWriter.Write(json);

我还建议从您自己的Object反序列化而不是串联的字符串文字。这使得形成JSON变得更容易,更安全。