3

I'm able to return a stringified Javascript object to my C# project. The string looks like this:

{"QuestionId":"","QuestionTitle":"hiu","OriginalURL":"","OriginalTitle":"","ChronicID":""}

How can I easily convert this to an Object with these parameters in C#?

UPDATE: I got it working. See code below.

SearchQuery search = (SearchQuery)JsonConvert.DeserializeObject(@filterParams, typeof(SearchQuery));
0

3 Answers 3

8

Using Json.Net

dynamic dynObj = JsonConvert.DeserializeObject(jsonstr);
Console.WriteLine("{0} {1}", dynObj.QuestionId, dynObj.QuestionTitle);

using JavaScriptSerializer

JavaScriptSerializer serializer = new JavaScriptSerializer();
var obj = serializer.Deserialize<Dictionary<string,object>>(jsonstr);
Console.WriteLine("{0} {1}", obj["QuestionId"], obj["QuestionTitle"]);

EDIT

string jsonstr = @"{""QuestionId"":""123"",""QuestionTitle"":""hiu"",""OriginalURL"":"""",""OriginalTitle"":"""",""ChronicID"":""""}";
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, that is interesting and helps me understand what is going on
@user1274649 I tested them both before I posted. And not working isn't very explanatory.
Thanks for your help. So this is the actual string as it appears in VS:
"\"QuestionId\":\"123\",\"QuestionTitle\":\"title\",\"OriginalURL\":\"\",\"OriginalTitle\":\"\",\"ChronicID\":\"\"}"
this is what happens when i try to convert such a string "'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'QuestionId'" and this is what I tried implementing: f (filterParams != null) { dynamic search = JsonConvert.DeserializeObject(filterParams); Console.WriteLine("{0} {1}", search.QuestionId, search.QuestionTitle); }
|
2

You want a JSON library for .NET. JSON stands for JavaScript Object Notation, and it's basically what you pasted in your question.

I personally like Json.NET.

FYI, a "prettier" way to display the object from your question is:

{
   QuestionId: '',
   QuestionTitle: 'hiu',
   OriginalURL: '',
   OriginalTitle: '',
   ChronicID: ''
}

3 Comments

Thanks, you answered my question. Turns out JSON libraries are already included in the project I'm working on. :)
EDIT: what do you mean display? That is the way the string appears in my code, so I need to parse it as is.
I just meant that it's easier to read if it's all tabbed out like that. JSON parsers don't care if it's all on one line or not, it's just for human readability.
2

You're looking for a JSON parser

1 Comment

How is this helpful? At least link to one...?

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.