Hooman Hooman - 3 months ago 14
C# Question

"object" does not contain a definition for 'Name'

i am using Json.Net package and my problem is when i want to get the value of an index it gives me an error like this "'object' does not contain a definition for 'Name'"

here is my GetData.cs file content:

using System;
using System.Web;
using System.Net;
using Newtonsoft.Json;

public class GetData
{
public string Name{set;get;}
public string ReleaseDate{set;get;}

public object GetBasic(){

string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00'}";

GetData Data = JsonConvert.DeserializeObject<GetData>(json);
return Data;

}

}


and this is my test.cshtml file content:

@{
GetData Data = new GetData();
var objects = Data.GetBasic();
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
@objects.Name
</body>
</html>


thank you in advance for help

Answer

You can do this in three ways, first one is by changing the return type of the GetBasic from object to GetData then the signature of the method will looks like the following:

public GetData GetBasic()
{
   // do Something here
}

In this case you need not to change anything more, your code will works fine as you expected.

Second option for you is change the method call without changing the method definition, which will looks like the following:

 GetData objects = (GetData)Data.GetBasic();

Which will Work since GetData having field called Name.

Third option is make GetBasic as a constructor like the following:

 public object GetData()
 {

     string json = @"{
          'Name': 'Bad Boys',
          'ReleaseDate': '1995-4-7T00:00:00'}";

     GetData Data = JsonConvert.DeserializeObject<GetData>(json);
     return Data;
 }

So that you can use like this:

 GetData DataObjects = new GetData();
 // DataObjects.Name will have the expected value