首页 > 解决方案 > 为 ElasticSearch 转义 JSON

问题描述

语境

我有一个在本地运行的 ElasticSearch 集群,我想序列化要发布到数据存储区的对象列表。

序列化按我的预期工作 - 就将数据输入 JSON 而言。

JsonConvert.SerializeObject(obj)ES 不喜欢转义字符串的事实。

我试过Regex.Unescape(str)了,但没有成功。

有任何想法吗?

代码片段

public static string GetAllTickets(string sessionToken, TicketResponse response, int eventId)
    {
        var tickets = new List<Ticket>();

        tickets.AddRange(response.tickets);

        if(response.info.total_pages > 1)
        {
            for (int i = 2; i < response.info.total_pages; i++)
            {
                response = GetTicketPage(sessionToken, eventId, i);
                tickets.AddRange(response.tickets);
            }
        }
        var json = JsonConvert.SerializeObject(tickets);
        return json;
    }



public static void PostToElastic(string response, string index, int id)
    {
        try
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(string.Format("http://127.0.0.1:9200/{0}/{0}/{1}", index, id));
            webRequest.ContentType = "application/json";
            webRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
            {
                streamWriter.Write(@Regex.Unescape(response));
                streamWriter.Flush();
            }
            var httpResponse = (HttpWebResponse)webRequest.GetResponse();
        }
        catch (System.Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

调试信息

[{\"barcode\":\"K8Y4253QGI\",\"order_id\":1,\"customer_id\":1,\"first_name\":\"name\",\"last_name\":\"last_name\",\"email\":\"email\",\"ticket_name\":\"Test Ticket\",\"ticket_type_id\":1,\"purchased\":\"2013-03-28T19:53:33\",\"attended\":false,\"scanned_by\":null,\"scanned_date\":null}]

错误

{
"error": {
    "root_cause": [
        {
            "type": "mapper_parsing_exception",
            "reason": "failed to parse"
        }
    ],
    "type": "mapper_parsing_exception",
    "reason": "failed to parse",
    "caused_by": {
        "type": "not_x_content_exception",
        "reason": "Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes"
    }
},
"status": 400

}

标签: c#elasticsearchjson.net

解决方案


推荐阅读