Python 拥抱 REST API 在 .NET 中使用,JSON 看起来很奇怪

Python Hug REST API consumed in .NET, JSON looks weird

从 .net 使用 Hug REST 端点时 JSON 有嵌入的字符。下面发布了一个完整的失败示例。非常感谢任何帮助。

Python

@hug.post('/test')
def test(response, body=None):
    input = body.get('input')
    print('INSIDE TEST ' + input)

    if input:
        dict = {"lastname":"Jordan"}
        dict["firstname"] = input
        return json.dumps(dict, sort_keys=True, default=str)

.NET(只能使用.net 3.5)

private static object GetParsedData(string data)
{
    var posturl = "http://localhost:8000/test"; 
    try
    {
        using (var client = new WebClient())
        {
            // upload values is the POST verb
            var values = new NameValueCollection()
                         {
                             { "input", data },
                         };
            var response = client.UploadValues(posturl, values);
            var responseString = Encoding.UTF8.GetString(response);
            var settings = new JsonSerializerSettings
                           {
                               NullValueHandling = NullValueHandling.Ignore,
                               MissingMemberHandling = MissingMemberHandling.Ignore
                           };
            JObject rss = JObject.Parse(responseString);
            Console.WriteLine((string)rss["lastname"]);
        }
    }
    catch (WebException ex)
    {
        if (ex.Response is HttpWebResponse)
        {
            var code = ((HttpWebResponse)ex.Response).StatusCode;
            var desc = ((HttpWebResponse)ex.Response).StatusDescription;
        }
        //_logger.Error(ex.Message);
    }
    return false;
}

responseString 看起来像这样:

"\"{\\"firstname\\": \\"Mike\\", \\"lastname\\": \\"Jordan\\"}\""

JObject.Parse 抛出错误:

Newtonsoft.Json.JsonReaderException: 
'Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 53.

解决方法 - 如果我做这样可怕的事情来正确解析 responseString JObject:

str = str.Replace("\", "");
str = str.Substring(1, len - 2);

怎么回事?

默认拥抱output format是json;没有必要在 return 值上调用 json.dumps,拥抱会自动执行此操作。