Niels
Niels

Reputation: 2596

NewtonSoft.JSON deserializing not working

I have the following JSON string:

{
  [    
    {
        "error": {
                     "typeofdevice": 678,
                     "valueconvert": "",
                     "message": "oops something went wrong"
                 }
    }
  ]
}

What is the best way to deserialize this and get the the value for 'Message'?

I tried:

JToken token = JArray.Parse(args.Result);
string message = (string)token["description"];

But then it says

the Array is missing an index, and its not working.

Rookie question I know.. But I can't figure it out :S.

Grtz.

Upvotes: 0

Views: 2196

Answers (2)

Bura Chuhadar
Bura Chuhadar

Reputation: 3751

In addition, if you want to check your JSON data if it is correct or not, you can send your data here:

http://jsoneditoronline.org/index.html

Upvotes: 0

Ramanpreet Singh
Ramanpreet Singh

Reputation: 860

using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    using Newtonsoft.Json;

    internal class Program
    {
        private static void Main(string[] args)
        {
            string jsonString =
                "["
                + "{"
                + " \"error\": "
                + "     {" 
                + "         \"typeofdevice\": 678,"
                + "         \"valueconvert\": \"\"," 
                + "         \"message\": \"oops something went wrong\"" 
                + "     }" 
                + "}" 
              + "]";

            List<Data> data = JsonConvert.DeserializeObject<List<Data>>(jsonString);
            Console.WriteLine(data[0].Error.typeofdevice);
        }

        public class Data
        {
            public Error Error { get; set; }
        }

        public class Error
        {

            public string typeofdevice { get; set; }
            public string valueconvert { get; set; }
            public string message { get; set; }
        }
    }
}

The above console app works but I have changed your JSON string as others rightly pointed out that its not valid JSON.

Upvotes: 1

Related Questions