JSON in C#; Sending and receiving data
Asked Answered
A

3

16

I am trying to make a desktop client for Request and Response application.

I am able to do GET requests easily. But I was wondering whether someone could help me work out how I could do a JSON request and response. and parse it to a string, from there I can workout how to slit it all up

Adversary answered 16/1, 2010 at 12:11 Comment(0)
F
13

Json.net is ubiquitous in the .net world.

Forgot answered 16/1, 2010 at 12:40 Comment(5)
Which part of Json.net provides tools for sending/receiving data on the desktop?Comfort
I would hazard to guess that often times JavaScriptSerializer is more often used than Json.net, I'd hardly call it ubiquitous. Only people who do transformations or queries on the data would really need Json.net. Still useful information, however.Duodenal
Json.NET is now the built in JSON serializer (as of .NET 4.5)Comfort
@ChrisS: What do you mean exactly?Pascoe
@Pascoe correction, it's just the web api: forums.asp.net/p/1810654/5010838.aspx/…Comfort
C
20

Small update:

As an alternative to System.Web or JSON.net, there's also JSONFX and ServiceStack.Text


For a desktop application one solution for making a JSON request is below. There may be an API somewhere to already do this but I haven't found any.

The desktop app

'Test' is just here to demonstrate passing parameters. JavaScriptSerializer is found in System.Web.Extensions.dll.

HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create("http://localhost:2616/Default.aspx/JsonTester");
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json, text/javascript, */*";
request.Method = "POST";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write("{id : 'test'}");
}

WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
string json = "";

using (StreamReader reader = new StreamReader(stream))
{   
    while (!reader.EndOfStream)
    {
        json += reader.ReadLine();
    }
}

// 3.5+ adds 'D' to the result, e.g.
// {"d":"{\"Name\":\"bob\",\"Age\":20,\"Foods\":[\"cheeseburger\",\"caviar\"]}"}
// So it thinks it's a dictionary with one key/value
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> x = (Dictionary<string, object>)serializer.DeserializeObject(json);
MyData data = serializer.Deserialize<MyData>(x["d"].ToString());

Default.aspx in the ASP.NET webapplication:

[WebMethod]
public static string JsonTester(string id)
{
    JavaScriptSerializer ser = new JavaScriptSerializer();

    var jsonData = new MyData()
    {
        Name = "bob",
        Age = 20,
        Foods = new List<string>()
    };

    jsonData.Foods.Add("cheeseburger");
    jsonData.Foods.Add("caviar");

    var result = ser.Serialize(jsonData);
    return result;
}

The MyData object

MyData appears in both the web app and the console app, but you'll want to put it in its own assembly as your domain object and reference it in the two places.

public class MyData
{
    public string Name { get; set; }
    public int Age { get; set; }
    public IList<String> Foods { get; set; }
}
Comfort answered 16/1, 2010 at 14:2 Comment(0)
F
13

Json.net is ubiquitous in the .net world.

Forgot answered 16/1, 2010 at 12:40 Comment(5)
Which part of Json.net provides tools for sending/receiving data on the desktop?Comfort
I would hazard to guess that often times JavaScriptSerializer is more often used than Json.net, I'd hardly call it ubiquitous. Only people who do transformations or queries on the data would really need Json.net. Still useful information, however.Duodenal
Json.NET is now the built in JSON serializer (as of .NET 4.5)Comfort
@ChrisS: What do you mean exactly?Pascoe
@Pascoe correction, it's just the web api: forums.asp.net/p/1810654/5010838.aspx/…Comfort
C
3

Look into the System.Web.Script.Serialization.JavaScriptSerializer class in the System.Web.Extensions.dll assembly.

It contains the Serialize and Deserialize< T > methods which are fairly straight-forward to use.

Calciferous answered 16/1, 2010 at 12:35 Comment(1)
The type or namespace name 'Script' does not exist in the namespace 'System.Web'Depot

© 2022 - 2024 — McMap. All rights reserved.