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
                }
            ]
        }
    ]
}
3
  • 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. Commented Jun 1, 2011 at 17:27
  • Duplicate of this? Commented Jun 1, 2011 at 17:28
  • possible duplicate of Generics / JSON JavaScriptSerializer C# Commented Jun 1, 2011 at 17:30

3 Answers 3

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 . . .
Sign up to request clarification or add additional context in comments.

1 Comment

This seem like the exact thing I needed. I have no idea how I missed it! Thank you so much.
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

Comments

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.

1 Comment

I agree. Why invent the wheel?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.