CS0029-Cannot implicitly convert type 'Newtonsoft.Json.Linq.JObject'

C#.Net Error 3

In this example we are going to read the JSON string using Newtonsoft.Json library with JObject class. You can download Newtonsoft.Json reference from NuGet package. 

Error Message:

Severity Code Description Project File Line Suppression State
Error CS0029 Cannot implicitly convert type 'Newtonsoft.Json.Linq.JObject' to 'ConsoleApp1.Employee' ConsoleApp1 C:\ConsoleApp1\ConsoleApp1\Program.cs 13 Active


Error Description:

using Newtonsoft.Json.Linq;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string empData=@"{'Name':'Ranga','Salary':'100'}";
            Employee obj = new Employee();
            obj = JObject.Parse(empData);
            Console.WriteLine("EmpName: " + obj.Name + " with Salary: " + obj.Salary);
            Console.Read();
        }
    }
    class Employee
    {
        public string Name { get; set; }
        public int Salary { get; set; }
    }
}

In the above code there is a issue in below line, JObject.Parse method can't directly assign values to the Object here. Instead of object we need to use dynamic keyword. Below solution is having complete program. Here no need of Employee object, dynamic will take care of the things.

obj = JObject.Parse(empData);

Solution:

Need to use dynamic keyword since JObject.Parse is returning JObject.

using Newtonsoft.Json.Linq;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string empData=@"{'Name':'Ranga','Salary':'100'}";
            dynamic obj = JObject.Parse(empData);
            Console.WriteLine("EmpName: " + obj.Name + " with Salary: " + obj.Salary);
            Console.Read();
        }
    }
    
}

Output: 



Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar