1

I try de-serialize using method with JavaScriptSerializer but it doesnt work. Not sure what is diffrent between my code and this example.

public void Main()
            {
              var dataResponse =@"{\"access_token\": \"NAonCg8KBHBpYXMSABoAJRAluFUSFAD2I2fXOrgvxInfWWG0UUsoqsby\", \"expires_in\": 28800}"

              JSON elements = new JavaScriptSerializer().Deserialize<JSON>(dataResponse);

              foreach (var item in elements.data) 
              {
                 MessageBox.Show(item.access_token.ToString());
              }

            } 
        public class JSON
            {
                public List<JSONElements> data { get; set; }
            } 
        public class JSONElements
            {
                public string access_token { get; set; }
                public int expired_in { get; set; }
            } 
2
  • 3
    What error do you get? Commented Jul 29, 2015 at 9:45
  • 2
    try using this. var dataResponse =@"{data: [{'access_token': 'NAonCg8KBHBpYXMSABoAJRAluFUSFAD2I2fXOrgvxInfWWG0UUsoqsby', 'expired_in': 28800}]}" also would be better if you use JsonConvert.DeserializeObject<>() Commented Jul 29, 2015 at 9:55

2 Answers 2

2

First:

Your json string doesn't match properties in JSONElements class.The int member name is different.

Second:

Use JSON.Net while working with json.And you're deserializing to a Wrong type. Your json string doesn't contain any property data.It is an JSONElements object instead.

Third:

If you use the @ symbol with a string then you cannot escape characters

So try like:

    var dataResponse =@"{'access_token':'NAonCg8KBHBpYXMSABoAJRAluFUSFAD2I2fXOrgvxInfWWG0UUsoqsby','expires_in':28800}";    
    var data = JsonConvert.DeserializeObject<JSONElements>(dataResponse);

And it works.

enter image description here

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

2 Comments

thank you for help and points i will correct it. But I cannot use JSON.NET.
You can use anything for this task, while JSON.Net is most popular and preferred way. Also, if you find the answer helpful, mark it as an answer.
0

Check string encoding. Maybe something like this will work

var dataResponse =@"{""access_token"": ""NAonCg8KBHBpYXMSABoAJRAluFUSFAD2I2fXOrgvxInfWWG0UUsoqsby"", ""expires_in"": ""28800""}";

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.