0

我正在尝试使用以下代码在我的 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\":[\"意外字符 ('!' (code 33)): 在 [Source: org.apache.catalina.connector.CoyoteInputStream@1ac4eeea; 行:1,列:52]\"]}"

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

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

那么,我的代码有什么问题?

4

1 回答 1

3

转义引号似乎存在问题。

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 的 JavaScriptSerializer 类。此类提供了一种安全、快速的方式来创建有效的 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"}}}
于 2013-05-03T15:13:33.440 回答