iShareHappyCode
iShareHappyCode

Reputation: 255

Unexpected character encountered while parsing value: 筛

I am returning Chinese characters from Web Api and following code used to parse the response.

        StringBuilder sb = new StringBuilder();
        byte[] buf = new byte[8192];
        string tempString = null;

        var request = (HttpWebRequest)HttpWebRequest.Create(endpoint);
        request.Accept = "application/json";
        request.ContentType = "application/json";
        request.Method = method;
        var inputSerializer = new DataContractJsonSerializer(typeof(T));
        var outputSerializer = new DataContractJsonSerializer(typeof(T[]));
        var requestStream = request.GetRequestStream();
        inputSerializer.WriteObject(requestStream, pun);
        requestStream.Close();

        var response = request.GetResponse();
        Stream resstream = response.GetResponseStream();

        int count = 0;
        do
        {
            count = resstream.Read(buf, 0, buf.Length);
            if (count != 0)
            {
                tempString = Encoding.Unicode.GetString(buf, 0, count);
                sb.Append(tempString);
            }
        }
        while (count > 0);
        {
            //Response.Write(sb.ToString() + "<br/><br/>");
            // string[] val = sb.ToString().Split('"');
        }



        if (response.ContentLength == 0)
        {
            response.Close();
            return default(T[]);
        }

        T[] responseObject = JsonConvert.DeserializeObject<T[]>(sb.ToString());

Unexpected character encountered while parsing value: 筛 It works fine for ENGLISH but not for Chinese. I am sure it's encoding issue. Need help

I refereed Unexpected character encountered while parsing value but no clue

Upvotes: 0

Views: 1916

Answers (1)

Julien Jacobs
Julien Jacobs

Reputation: 2629

I built a quick sample test with a Web API controller that would return some Chinese string, and use a changed version of your client code to read the response.

The response was indeed garbage characters when using Unicode encoding. Changing it to UTF8 as shown below fixed the problem.

tempString = Encoding.UTF8.GetString(buf, 0, count);

Note that most of times, the encoding for XML/JSON is UTF8 unless the service is really doing some Unicode (UTF16 Little Endian)

Upvotes: 1

Related Questions