0

I write this code for read json in httphandler:

var jsonSerilizer = new JavaScriptSerializer();
            var jsonString = String.Empty;
            context.Request.InputStream.Position = 0;
            using (var inputStream = new StreamReader(context.Request.InputStream))
            {
                jsonString = inputStream.ReadToEnd();
            }


and my json string is:

{"r_id":"140","name":"d","count":"5","c_id":"150"} 


and i use this method for parse json string:

JavaScriptSerializer j = new JavaScriptSerializer();
            dynamic a = j.Deserialize(jsonString, typeof(object));
            string r_id = a["r_id"];
            string Name = a["name"];
            string count = a["count"];
            string c_id = a["c_id"];


up code parse my json string to :
r_id:140
name:d
count:5
c_id:50

When client send me array of string json for example :

{"r_id":"140","name":"d","count":"5","c_id":"150"}
{"r_id":"150","name":"der","count":"50","c_id":"150"}


i can parse up json string
How can i?
I use this code:

 var jsonSerilizer = new JavaScriptSerializer();
            var jsonString = String.Empty;
            context.Request.InputStream.Position = 0;
            using (var inputStream = new StreamReader(context.Request.InputStream))
            {
                jsonString = inputStream.ReadToEnd();
            }
            File.AppendAllText(@"d:\status\LOL.txt", "GetJSON to FROM:"+ jsonString+"\r\n", Encoding.UTF8);
            JavaScriptSerializer j = new JavaScriptSerializer();
            dynamic a = j.Deserialize(jsonString, typeof(List<ClientMessage>));
            foreach (var obj in a)
            {
                File.AppendAllText(@"d:\status\LOL.txt", obj.name + "\r\n", Encoding.UTF8);
            }


but when program recieve to File.AppendAll.. program crash and down.

  • Your question isn't very clear. Are you having trouble parsing those JSON strings? If so, what is your issue? You need to be specific in describing your problem. – mason Aug 06 '14 at 13:39

3 Answers3

0

First of all try to create a model ( class to hold your objects) like this :

Class ClientMessage {
           public string   r_id {get;set;}
          public string name {get;set;}
            public string count {get;set;}
            public string c_id {get;set;}
}

In this case you would receive a List , so try to do it like this :

JavaScriptSerializer j = new JavaScriptSerializer();
            dynamic a = j.Deserialize(jsonString, typeof(List<ClientMessage>));

// and then iterate on your object

foreach (var obj in a)
{
//start assigning values


}
Adam
  • 2,973
  • 25
  • 22
  • thanks my friends,but how can i write code in foreach loop for example string name=ob[i].text? – user3851833 Aug 06 '14 at 13:44
  • @wizperr i write obj.name but program is crash! – user3851833 Aug 06 '14 at 14:06
  • i copy and paste your code and customize to my code,and into the foreach loop write a simple str+=obj.name and when client send json,program get a string json but when recieve into foreach loop program goto catch block. – user3851833 Aug 06 '14 at 14:09
  • whats the exception msg ur getting in the catch ? – Adam Aug 06 '14 at 14:10
  • catch=System.ArgumentException: Invalid JSON primitive: "r_id":"25","name":"ka","count":"2","c_id":"150"}. at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at Portal.Get_O.ProcessRequest(HttpContext context) – user3851833 Aug 06 '14 at 14:13
  • Oh i see, please use JSON.stringify when you post ur json from the page – Adam Aug 06 '14 at 14:15
  • thanks to pay attention to me my friend,i write code in c# for client and when send the json,json type is string and this json string send :{"r_id":"25","name":"ka","count":"2","c_id":"150"} – user3851833 Aug 06 '14 at 14:16
  • right, but when you post Json it has to come from Javascript, therefore you have to use JSON.stringify, even if you think its string – Adam Aug 06 '14 at 14:18
  • i use this tutorial for my client:http://stackoverflow.com/questions/9145667/how-to-post-json-to-the-server – user3851833 Aug 06 '14 at 14:19
  • I see, in that case, try to formulate your object there and serialize it, according to your tutorial it should look something like this: using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { ClientMessage msg=new ClientMessage(); msg.r_id="123"; msg.name="gd"; msg.count="5"; msg.c_id="45"; List _list=new List();_list.add(msg) //serialize it string json = JsonConvert.SerializeObject(_list).ToString(); streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); – Adam Aug 06 '14 at 14:40
0

I would suggest creating an object you can parse your JSON into, so something like:

public MyClass {

    public int r_id { get; set;}
    public string name { get; set; }
    // etc
}

This will allow you to parse directly into that object, like this:

var results = j.Deserialize<List<MyClass>>(jsonString);
dougajmcdonald
  • 17,178
  • 7
  • 49
  • 87
0

Can you try something this code, I am assuming you are getting json data like below.

[
    {
        r_id: "123",
        name: "deepu",
        count:"5",
        c_id:"150"
    },
    {
        r_id: "444",
        name: "aaa",
        count:"25",
        c_id:"55"
    },
    {
        r_id: "5467",
        name: "dfgdf",
        count:"5",
        c_id:"3434"
    }
]

I am using the above Client Message class here and adding JsonProperty attribute.

public class ClientMessage
{
    [JsonProperty("r_id")]
    public string RId { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("count")]
    public string Count { get; set; }

    [JsonProperty("c_id")]
    public string Cid { get; set; }
}

Finally, get the json data fort testing, I am reading the data from external file..

var data = System.IO.File.ReadAllText("jsondata.txt");
var jsResult = JsonConvert.DeserializeObject<List<ClientMessage>>(data);

NOTE : You need to add Newtonsoft.Json reference in your project

Deepu Madhusoodanan
  • 1,455
  • 1
  • 14
  • 25