0

When consuming a Hug REST endpoint from .net JSON has embedded characters. A complete failing example posted below. Any help greatly appreciated.

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 (can only use .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 looks like this:

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

JObject.Parse throws error:

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

Workaround - If I do something horrible like this to responseString JObject parses correctly:

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

Whats going on?

  • Looks double-encoded - what happens if the view function just returns a `dict`? – snakecharmerb May 09 '19 at 17:27
  • [snakecharmerb](https://stackoverflow.com/users/5320906/snakecharmerb) you are awesome! Thank you so much. Can't tell you how many hours I wasted on this - ugh. Yes, apparently Hug automatically JSON serializes the return value as default output format, which is cool. Please post this as an answer and I will mark it as answered. Thanks again!! On the plus side, I kinda posted a mini tutorial bridging two worlds ;) – Impostor Syndrome May 09 '19 at 17:44
  • 1
    Your response from python is getting serialized twice – Kunal Mukherjee May 09 '19 at 17:44
  • Thank you Kunal. You are right. – Impostor Syndrome May 09 '19 at 18:09

1 Answers1

1

The default hug output format is json; it is not necessary to call json.dumps on return values, hug will do this automatically.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153