views:

137

answers:

3

I am querying a web service that was built by another developer. It returns a result set in a JSON-like format. I get three column values (I already know what the ordinal position of each column means):

[["Boston","142","JJK"],["Miami","111","QLA"],["Sacramento","042","PPT"]]

In reality, this result set can be thousands of records long.

What's the best way to parse this string?

I guess a JSON deserializer would be nice, but what is a good one to use in C#/.NET? I'm pretty sure the System.Runtime.Serialization.Json serializer won't work.

+1  A: 

How about this?

Jonathan Feinberg
This worked, but I'm going to try the other methods also.
Jeff Meatball Yang
A: 

It sounds like you have a pretty simple format that you could write a custom parser for, since you don't always want to wait for it to parse and return the entire thing before it uses it.

I would just write a recursive parser that looks for the tokens "[", ",", "\"", and "]" and does the appropriate thing.

Eric Normand
Is this simple? Can you provide some links or example code?
Jeff Meatball Yang
+1  A: 

Using the built in libraries for asp.net (System.Runtime.Serialization and System.ServiceModel.Web) you can get what you want pretty easily:

string[][] parsed = null;
var jsonStr = @"[[""Boston"",""142"",""JJK""],[""Miami"",""111"",""QLA""],[""Sacramento"",""042"",""PPT""]]";
using (var ms = new System.IO.MemoryStream(System.Text.Encoding.Default.GetBytes(jsonStr)))
{
    var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(string[][]));
    parsed = serializer.ReadObject(ms) as string[][];
}

A little more complex example (which was my original answer) First make a dummy class to use for serialization. It just needs one member to hold the result which should be of type string[][].

[DataContract]
public class Result
{
    [DataMember(Name="d")]
    public string[][] d { get; set; }
}

Then it's as simple as wrapping your result up like so: { "d": /your results/ }. See below for an example:

Result parsed = null;
var jsonStr = @"[[""Boston"",""142"",""JJK""],[""Miami"",""111"",""QLA""],[""Sacramento"",""042"",""PPT""]]";
using (var ms = new MemoryStream(Encoding.Default.GetBytes(string.Format(@"{{ ""d"": {0} }}", jsonStr))))
{
    var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Result));
    parsed = serializer.ReadObject(ms) as Result;
}
Josh
THanks, your simple example worked well. I don't need the complex stuff - but good to know.
Jeff Meatball Yang