14

I have a JSON string

{
  "Date":"21/11/2010"
  "name": "TEST"
  "place":"xyz"
}

I want to convert it into a C# dictionary without using a third party library

9
  • 6
    maybe you can use a second-party Commented Aug 8, 2013 at 7:52
  • 8
    Do not downvote because you dislike the choice to use no 3rd Party libs. Maybe there is a good reason for. So clarify before judging Commented Aug 8, 2013 at 7:56
  • 1
    No there's not. You do not have to reinvent the wheel everytime. But if he wants to, then he should show us his effort and the exact problem. Commented Aug 8, 2013 at 8:01
  • 1
    Shouldn't those prop-value pairs be comma-separated? Commented Aug 8, 2013 at 8:06
  • 1
    Sometimes understanding what a framework does is quite helpful instead blindly using it. So learning would be a reason not to choose a whole API for just one small feature. Commented Aug 8, 2013 at 10:26

2 Answers 2

29

You can do it natively since net 3.5 with jsonserializer.

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string,string>>(jsonText);
var place = dict["place"]; // "xyz"

Here is a simple tutorial for your case: Quick JSON Serialization/Deserialization in C#

Requires the System.Web.Extensions reference. If you can't find it, your program is probably using a Client target framework. Use a "Full" target framework.

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

4 Comments

THX xanatos am on my Smartphone so editing is quite unconvenient. Nice work
that doesn't work for me (VS2010). it breaks with the error "No parameterless constructor defined for type of 'System.String'"
@zewa666 Thanks man!! I spent 4 hours behind this and found extremely good solution. This solution follows KISS principal.
Same problem as @ekkis, doesn't work for me as shown, however, using <string, dynamic> or just dynamic as show when you follow the tutorial link does.
1

You can now (for a while) use the inbuilt System.Text.Json for this as follows:

var dict = JsonSerializer.Deserialize<Dictionary<string, string>>(jsonString);

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.