7

I've read lots of tutorials on how to deserialize a JSON object to an object of a particular using DataContractJsonSerializer. However, I'd like to deserialize my object to a Dictionary consisting of either Strings, Arrays or Dictionaries, such as System.Json does with SilverLight when I say JsonObject.Parse(myJSONstring).

Is there an equivalent to System.Json that I can use in my WPF project?

(just a short background: I'm fetching JSON objects that have way to much info, and I just want to use a little bit to fill out a String array)

Cheers

Nik

4 Answers 4

9

Just use .NET's built-in JavaScriptSerializer.

var jss = new JavaScriptSerializer();
var data = jss.Deserialize<dynamic>(jsonString);

//"data" actually implements IDictionary<string, object>
var p1 = data["Property1"];
var p2 = data["Property2"];

Don't forget to reference "System.Web.Extensions"

Sign up to request clarification or add additional context in comments.

Comments

3

Take a look at the C# section (scoll to the bottom) of http://json.org/, they have several implementations of serializers and parsers that should help.

Comments

1

I successfully use JayRock: http://jayrock.berlios.de/

public class JayRockMarshaller : IMarshaller
{
    public ICollection Read(string text)
    {
        return (ICollection)new ImportContext().Import(new JsonTextReader(new StringReader(text)));
    }

    public string Write(ICollection objectToMarshal)
    {
        var writer = new StringWriter();
        new ExportContext().Export(objectToMarshal, new JsonTextWriter(writer));
        return writer.ToString();
    }
}

Works for both Dictionaries and Lists like a dream.

Comments

0

Also look at https://github.com/jlarsson/Kiwi.Json it handles all sorts of datatypes and you can easily create your own converter if the built in doesn't fit.

There's blog where you can find samples on this for example: http://dancewithcode.wordpress.com/2012/03/24/case-study-custom-json-converter-for-datatable/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.