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; }
            } 
Community
  • 1
  • 1
Jakub
  • 11
  • 1
  • 3
    What error do you get? – Kimtho6 Jul 29 '15 at 09:45
  • 2
    try using this. `var dataResponse =@"{data: [{'access_token': 'NAonCg8KBHBpYXMSABoAJRAluFUSFAD2I2fXOrgvxInfWWG0UUsoqsby', 'expired_in': 28800}]}"` also would be better if you use `JsonConvert.DeserializeObject<>()` – Nilesh Jul 29 '15 at 09:55

2 Answers2

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

Alex Neves
  • 616
  • 1
  • 7
  • 16
Amit Kumar Ghosh
  • 3,618
  • 1
  • 20
  • 24
  • thank you for help and points i will correct it. But I cannot use JSON.NET. – Jakub Jul 29 '15 at 10:24
  • 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. – Amit Kumar Ghosh Jul 29 '15 at 10:26
0

Check string encoding. Maybe something like this will work

var dataResponse =@"{""access_token"": ""NAonCg8KBHBpYXMSABoAJRAluFUSFAD2I2fXOrgvxInfWWG0UUsoqsby"", ""expires_in"": ""28800""}";
Piotr Pasieka
  • 2,063
  • 1
  • 12
  • 14