0

I need to convert a string to an object, just like how model binding happens in MVC controllers.
so if I have a string of json like this:

{
  "name": "tom",
  "job": "developer",
  "projects": ["projectOne", "projectTwo"]
}

I could the convert it to this object:

public class Developer
{
  public string name {get; set;}
  public string job {get; set;}
  public string[] projects {get; set;}
}

something like this:

Developer developer = Convertor.TryConvert<Developer>(myJson);

so is there any library or function that can do this?

5
  • 8
    You should check : newtonsoft.com/json Commented Mar 8, 2016 at 19:39
  • @JonasW could you post an answer so I can make it the right answer? Commented Mar 8, 2016 at 19:49
  • I guess I don't understand your question, you've tagged this question with MVC, why not just let MVC model bind it? Commented Mar 8, 2016 at 20:48
  • @MohsenShakiba sry for late answer.. I have posted a answer now. Commented Mar 8, 2016 at 21:02
  • You do realize that the MVC framework does all this automatically? If the method you posting back to has a parameter Developer model then the model will be bound. Commented Mar 8, 2016 at 21:25

2 Answers 2

2

You should check this out : http://www.newtonsoft.com/json

Sample :

string json = @"{
                   "name": "tom",
                   "job": "developer",
                   "projects": ["projectOne", "projectTwo"]
                 }";

Developer d = JsonConvert.DeserializeObject<Developer>(json);
Sign up to request clarification or add additional context in comments.

Comments

2

Look here: How to Convert JSON object to Custom C# object?

Basically one of the answers is:

JavaScriptSerializer jss = new JavaScriptSerializer();
Developer user = jss.Deserialize<Developer>(jsonString); 

1 Comment

really good answer but sadly I could only choose one correct answer. did vote you up though, thanks a lot

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.