1

the code below does not return any errors but still does not convert the JSON to object

JSON string I got from an API

{
    "genres": [
        {
            "id": 28,
            "name": "Action"
        },
        {
            "id": 12,
            "name": "Adventure"
        }
    ]
}

General Test Class

    public class Test
    {
        public int id;
        public string Name;
    }

the code below shows how I tried to convert the JSON string to List of Test class

            string JsontStr = GenreService.get();
            var Serializer = new JavaScriptSerializer();
            List<Test> a = (List<Test>)Serializer.Deserialize(JsontStr, typeof(List<Test>));

an image of what the object a has in it when the program has finished running

Yovel
  • 93
  • 7
  • Use [How to auto-generate a C# class file from a JSON string](https://stackoverflow.com/q/21611674/3744182) to generate a correct data model. You need a root object `public class Welcome { public List Genres { get; set; } }` as shown in https://app.quicktype.io?share=YdFGzyTvueCwJfGBb3Op, which is one of the tools mentioned in the linked question's answers. – dbc Dec 05 '19 at 22:21

2 Answers2

1

The serializer is not working because the json is not an array of Test object. It is actually an array of Genres element. In your test class, Name has to be lower case to match the case from json string.

public class Test
{
    public int id {get;set;}
    public string name {get;set;}  // it should be all lowercase as well. Case matters
}

public class Genres 
{
    public List<Test> genres {get;set;}
}

string JsontStr = GenreService.get();
var Serializer = new JavaScriptSerializer();
Genres a = (Genres)Serializer.Deserialize(JsontStr, typeof(Genres));
Jawad
  • 11,028
  • 3
  • 24
  • 37
0

I made a little test of you case with a WebMethod and @Jawad answer is rigth.

The answer of the list of test objects is Genres, that is what I received from the test I did

genres: [{id: 28, name: "Action"}, {id: 12, name: "Adventure"}]

Because of that, I only have to declare a WebMethod like this

[WebMethod]
public static int JSONApi(List<Test> genres)

And the serialization is done automatically

Hope it helps to clarify your case.

leopansa
  • 3
  • 4