-1

I have below JSON data

{
   "appDesc": {
                "description": "App description.",
                "message": "Create and edit presentations "
              },
   "appName": {
                "description": "App name.",
                "message": "Slides"
              }
}

I want to Deserialize into C# class object. I am using JsonConvert.DeserializeObject<>() to achieve this functionality. But some how it is not working.

 string JsonData= System.IO.File.ReadAllText(msgJSONpath);

 var moreInfo = JsonConvert.DeserializeObject<appName>(msg)



internal class appName
{
    public string message { get; set; }

    public string description { get; set; }
}

So moreInfo object will have 2 properties in message and description.

JustLearning
  • 3,164
  • 3
  • 35
  • 52
AMIT SHELKE
  • 501
  • 3
  • 12
  • 34

3 Answers3

0

JObject defines method Parse for this:

JObject json = JObject.Parse(str);

or try for a typed object try:

Foo json  = JsonConvert.DeserializeObject<Foo>(str)
A.M. Patel
  • 334
  • 2
  • 9
0

you need 2 C# classes since the properties of appName and appDesc are exactly the same.

  1. To store appname

    public class appName {
      public string description { get; set; }
      public string message { get; set; }
    }
    
  2. A class to have both above classes as properties

    public class appResult {
      public appName appDesc { get; set; }
      public appName appName { get; set; }
    
      public appResult() {
        appDesc = new appName();
        appName = new appName();
      }
    }
    }
    
  3. desirialize the json

    var result = JsonConvert.DeserializeObject<appResult>(msg);
    
  4. Once you have the result object you can get your appName

    var appName = result.appName;
    
JustLearning
  • 3,164
  • 3
  • 35
  • 52
0

First ,you need to create some classes based on your JSON , if you,re using visual studio you can copy the JSON string to your clipboard and than go to

Edit > Paste Special > Paste JSON As Classes

otherwise you can use This Online Tool

after that your code should be something like this :

     string JsonData= System.IO.File.ReadAllText(msgJSONpath);

     var moreInfo = JsonConvert.DeserializeObject<RootObject>(msg);

Generated Classes Based On Your JSON :

    public class AppDesc
{
    public string description { get; set; }
    public string message { get; set; }
}

public class AppName
{
    public string description { get; set; }
    public string message { get; set; }
}

public class RootObject
{
    public AppDesc appDesc { get; set; }
    public AppName appName { get; set; }
}
FarhadMohseni
  • 395
  • 5
  • 8