Search code examples
c#asp.netjsonjsonserializer

Issue with Json Response in C# when RESPONSE write two fields in foreign language


i make web service in c# which write with HTTP RESPONE.WRITE json answer but the problem is when i return the json with some field which included the hebrew langauge , after that the json response is not full the end bracket miss.. i put the code in c# and the response of the json string

json response with hebrew fields

{"Response":"OK","FName":"איגור","LName":"kurylo","User_Name":"0524858214","ErrorMsg":"P

json response regulat with english fields :

{"Response":"OK","FName":"igor","LName":"kurylo","User_Name":"0524858218","ErrorMsg":"Pass"}

and thie my code in web service this the model of the json response

public class Android_Reg
{
    public string Response { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public string User_Name { get; set; }

    public string ErrorMsg { get; set; }   
}

string l = Convert.ToString(jSon.Serialize(reg).ToString().Length);
string jsonr = jSon.Serialize(reg).ToString();
var json = JsonConvert.SerializeObject(reg, Formatting.Indented);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.AddHeader("content-length", l);

HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Output.Write(jsonr);

thank you for help :)

EDIT: ok i do some test i debuig the my web service and i find out the next details after

 string jsonr = jSon.Serialize(reg).ToString();

this command the jsonr get the next string also with hebrew and english fields jsonr

"{\"Response\":\"OK\",\"FName\":\"igor\",\"LName\":\"kurylo\",\"User_Name\":\"0524858281\",\"ErrorMsg\":\"Pass\"}"


"{\"Response\":\"OK\",\"FName\":\"איגור\",\"LName\":\"קורילו\",\"User_Name\":\"0524858270\",\"ErrorMsg\":\"Pass\"}"

maybe becaouse the \ the string is truncated and i check out the lenght of both ofthe string the the first string is 92 charachters and the second is 92


Solution

  • I haven't been able to test this but I think the problem lies with the length of the string in the line HttpContext.Current.Response.AddHeader("content-length", l);

    The length of your Hebrew string is five and the number of missing characters is 5. To encode the Hebrew it will be using a double-byte encoding, hence the 5 missing characters. If you add to l the number of Hebrew characters I believe the problem will go away. To test it just use l + 5.