Jira发布错误 - 期望逗号分隔OBJECT条目

时间:2013-05-03 09:36:42

标签: c# json jira

我正在尝试使用以下代码在我的jira中创建新的项目问题,

using using System.Text;
using System.Net.Http;
using System.Json;
using System.Web.Script.Serialization;

namespace Test
{
    class Class1
    {
        public void CreateIssue()
        {
            string message = "Hai \"!Hello\" ";
            string data = "{\"fields\":{\"project\":{\"key\":\"TP\"},\"summary\":\"" + message +    "\",\"issuetype\":{\"name\": \"Bug\"}}}";
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.DefaultRequestHeaders.ExpectContinue = false;
            client.Timeout = TimeSpan.FromMinutes(90);
            byte[] crdential = UTF8Encoding.UTF8.GetBytes("adminName:adminPassword");
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(crdential));
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));     
            System.Net.Http.HttpContent content = new StringContent(data, Encoding.UTF8, "application/json");
            try
            {
                client.PostAsync("http://localhost:8080/rest/api/2/issue",content).ContinueWith(requesTask=>
                {
                    try
                    {
                        HttpResponseMessage response = requesTask.Result;
                        response.EnsureSuccessStatusCode();
                        response.Content.ReadAsStringAsync().ContinueWith(readTask =>
                        {
                            var out1 = readTask.Result;
                        });
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception.StackTrace.ToString());
                        Console.ReadLine();
                    }
                });
            }
            catch (Exception exc)
            {
            }
        }
    }
}

它会抛出如下错误:

  

“{\”errorMessages \“:[\”意外字符('!'(代码33)):期待逗号分隔OBJECT条目\ n在[来源:org.apache.catalina.connector.CoyoteInputStream@1ac4eeea ; line:1,column:52] \“]}”

但是我在Firefox Poster中使用相同的json文件,我已经创建了这个问题。

  

Json文件:{“fields”:{“project”:{“key”:“TP”},“summary”:“Hai \”!Hello \“”,\“issuetype \”:{\“name \“:\”Bug \“}}}”

那么,我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

转义引号似乎存在问题。

这是data变量初始化后的漂亮版本:

{
    "fields":{
        "project":{
            "key":"TP"
        },
        "summary":"Hai "!Hello" ",
        "issuetype":{
            "name": "Bug"
        }
    }
}

错误消息显示Unexpected character ('!')...was expecting comma...。查看漂亮打印的字符串,错误的原因变得清晰:

"summary":"Hai "!Hello" ",

JIRA使用的JSON解释器可能会解析此文本:

"summary":"Hai " ⇐ This trailing quotation mark ends the "summary" value
! ⇐ JSON expects a comma here
Hello" ", 

在您的C#代码中,您有:

string message = "Hai \"!Hello\" ";

感叹号前面的引号用反斜杠转义。但是,这只会转义C#编译器的引号。当C#编译器完成后,反斜杠就消失了。要在JSON字符串中嵌入引号,需要使用反斜杠后跟引号:

string message = "Hai \\\"!Hello\\\" ";

为了避免许多与JSON格式相关的陷阱,我强烈建议使用Microsoft's JavaScriptSerializer class。此类提供了一种安全,快速的方法来创建有效的JSON:

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace JsonTests
{
    class Program
    {
        static void Main(string[] args)
        {
            string message = "Hai \"!Hello\" ";

            var project = new Dictionary<string, object>();
            project.Add("key", "TP");

            var issuetype = new Dictionary<string, object>();
            issuetype.Add("name", "Bug");

            var fields = new Dictionary<string, object>();
            fields.Add("project", project);
            fields.Add("summary", message);
            fields.Add("issuetype", issuetype);

            var dict = new Dictionary<string, object>();
            dict.Add("fields", fields);

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string json = serializer.Serialize((object)dict);
            Console.WriteLine(json);
        }
    }
}

结果:

{"fields":{"project":{"key":"TP"},"summary":"Hai \"!Hello\" ","issuetype":{"name":"Bug"}}}