Home > other >  Json array to C# class
Json array to C# class

Time:11-17

I’ve got a very simple scenario. I have an api response that simply returns an array of strings.

[‘test’,’test2’,’test3’]

I need to deserialise into an object to integrate with some current code.

I’ve tried using a straight class with a single property of type List but no dice.

How to deserialise into single object?

CodePudding user response:

If you are using Visual Studio, you can try to use the Paste special - Paste JSON as classes under the Edit menu. Otherwise you can use this simple tool https://json2csharp.com/.

For deserialize the json string, you can use this two extension method:

using System.Runtime.Serialization.Json;
     public static T DeserializeFromJsonString<T>(this string data)
        {
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
                return stream.DeserializeFromJsonStream<T>();
        }
        public static T DeserializeFromJsonStream<T>(this Stream stream)
        {
            T result = (T)new DataContractJsonSerializer(typeof(T)).ReadObject(stream);
            return result;
        }

CodePudding user response:

if you need deserialise the api outPut into single object:

    class _object
    {
        public List<string> value { get; set; }
        public _object(List<string> val)=>
            value = val;
    }

     string[] apiOutput =  { "test", "test2", "test3" };
     _object myobject = new _object(apiOutput.ToList());

If you want to convert the array into a list of objects:

    class _object
    {
        public string value { get; set; }
        public _object(string val)=>
            value = val;
    }

    string[] apiOutput = {"test", "test2", "test3"};
    List<_object> listObjest = apiOutput.Select(x => new _object(x)).ToList();
    listObjest.ForEach(x=>Console.WriteLine(x.value));
  • Related