在c#中将json字符串传递给Rest服务(POST)时出现错误

本文关键字:POST 错误 服务 Rest json 中将 字符串 | 更新日期: 2023-09-27 18:06:18

我试图将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 - 04 - t22:40:55.645 + 0000"、"消息":"不可以从字符串值实例化java.util.LinkedHashMap类型的值(' {');没有单字符串构造函数/工厂方法'n at[来源:org.glassfish.jersey.message.internal.EntityInputStream@50e3274b;行:1,列:33](通过引用链:com.jamasoftware.contour.rest.v1.domain.RequestItem['"字段'])

"}}

在c#中将json字符串传递给Rest服务(POST)时出现错误

JSON数据是这样的

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

但是你实际上构建的是:

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

这是无效的JSON。

您当前以字符串形式发送fields,该字符串对于该属性的目标类型无效。去掉封装的引号,将this发送为一个对象。

例如:

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

我还建议从您自己的对象反序列化,而不是连接字符串字面值。这使得形成JSON更容易、更安全。