0

I've seen quite a few ways to output JSON in C#. None of them, however, seem easy. This may very well be due to my lack of knowledge of C#, though.

Question: If you were to write JSON (for use in JavaScript later on), how would you do it? I would prefer to not use third-party tools; however this is not an ultimatum of any kind. Is JSON doable in C# ASP.NET out of the box?

Example of JSON I wish to write:

{
    "Trips": [
        {
            "from": "here",
            "to": "there",
            "stops": [
                {
                    "place": "middle1",
                    "KMs": 37
                },
                {
                    "place": "middle2",
                    "KMs": 54
                }
            ]
        },
        {
            "from": "there",
            "to": "here",
            "stops": [
                {
                    "place": "middle2",
                    "KMs": 37
                },
                {
                    "place": "middle1",
                    "KMs": 54
                }
            ]
        }
    ]
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hejner
  • 372
  • 3
  • 15
  • Are you trying to serialize objects, write some json from a web site, or simply persist some data to a file in JSON format? You'll need to be more specific to get decent answers. – Justin Niessner Jun 01 '11 at 17:27
  • possible duplicate of [Generics / JSON JavaScriptSerializer C#](http://stackoverflow.com/questions/304081/generics-json-javascriptserializer-c) – manojlds Jun 01 '11 at 17:30
  • Duplicate of [this](http://stackoverflow.com/questions/6201529/turn-c-object-into-a-json-string-in-net-4)? – goalie7960 Jun 01 '11 at 17:28

3 Answers3

3

How about JavaScriptSerializer? Nice integrated solution, allowed to be expanded upon with JavaScriptConverters.


Demo of what you were after:

using System;
using System.Web.Script.Serialization;
using System.Text;

public class Stop
{
    public String place { get; set; }
    public Int32 KMs { get; set; }
}

public class Trip
{
    public String from { get; set; }
    public String to { get; set; }
    public Stop[] stops { get; set; }
}

public class MyJSONObject
{
    public Trip[] Trips { get; set; }

    public override String ToString()
    {
        StringBuilder sb = new StringBuilder();
        foreach (Trip trip in this.Trips)
        {
            sb.AppendFormat("Trip:\r\n");
            sb.AppendFormat("\t   To: {0}\r\n", trip.to);
            sb.AppendFormat("\t From: {0}\r\n", trip.from);
            sb.AppendFormat("\tStops:\r\n");
            foreach (Stop stop in trip.stops)
            {
                sb.AppendFormat("\t\tPlace: {0}\r\n", stop.place);
                sb.AppendFormat("\t\t  KMs: {0}\r\n", stop.KMs);
            }
            sb.AppendLine();
        }
        return sb.ToString();
    }
}
public class Test
{
    public static void Main()
    {
        String example = "{\"Trips\":[{\"from\":\"here\",\"to\":\"there\",\"stops\":[{\"place\":\"middle1\",\"KMs\":37},{\"place\":\"middle2\",\"KMs\":54}]},{\"from\":\"there\",\"to\":\"here\",\"stops\":[{\"place\":\"middle2\",\"KMs\":37},{\"place\":\"middle1\",\"KMs\":54}]}]}";

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        // Parse the string to our custom object
        MyJSONObject result = serializer.Deserialize<MyJSONObject>(example);
        Console.WriteLine("Object deserialized:\r\n\r\n{0}\r\n\r\n", result);

        // take our custom object and dump it in to a string
        StringBuilder sb = new StringBuilder();
        serializer.Serialize(result, sb);
        Console.WriteLine("Object re-serialized:\r\n\r\n{0}\r\n\r\n", sb);

        // check step
        Console.WriteLine(example.Equals(sb.ToString()) ? "MATCH" : "NO match");
    }
}

And the output:

Object deserialized:

Trip:
           To: there
         From: here
        Stops:
                Place: middle1
                  KMs: 37
                Place: middle2
                  KMs: 54

Trip:
           To: here
         From: there
        Stops:
                Place: middle2
                  KMs: 37
                Place: middle1
                  KMs: 54




Object re-serialized:

{"Trips":[{"from":"here","to":"there","stops":[{"place":"middle1","KMs":37},{"pl
ace":"middle2","KMs":54}]},{"from":"there","to":"here","stops":[{"place":"middle
2","KMs":37},{"place":"middle1","KMs":54}]}]}

MATCH
Press any key to continue . . .
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • This seem like the exact thing I needed. I have no idea how I missed it! Thank you so much. – Hejner Jun 01 '11 at 17:31
2

There is JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1)

http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

manojlds
  • 290,304
  • 63
  • 469
  • 417
1

You should really take a look at Json.NET

Not only does this library perform superbly it can parse JSON as well. Which means you can easily round trip stuff and communicate over JSON without involving a WCF service layer. It also does other neat things such as providing a queryable dynamic object model.

John Leidegren
  • 59,920
  • 20
  • 131
  • 152