Deserialize Json string [] to string []

4

I have the following JSON :

{"TicketID":["116","114","112","108","107","104","102"]}

When I try to deserialize to string[] I get the error:

  

Server Error in Application '/'.

     

No constructor without parameters   was set to the type of 'System.String []'. Description:   unhandled exception during the execution of the current Web request.   Examine the stack trace for more information about the   error and where it originated in the code.

     

Exception Details: System.MissingMethodException: No constructor   without parameters was defined for the type of 'System.String []'.

     

Source Error:

     

Line 130: // return   response.Result.Content.ReadAsStringAsync (). Result.ToString (); Line   131: Line 132: String [] TicketID = new   JavaScriptSerializer () .Deserialize (response.Result.Content.ReadAsStringAsync () .result);

I saw other answers about creating an object, but none of them solved the problem.

How can I extract a% of% of this string[] ?

    
asked by anonymous 22.12.2017 / 19:14

2 answers

3

Using the library Newtonsoft.Json which is one of the most used.

using System;
using Newtonsoft.Json;

namespace JsonProject
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "{\"TicketID\":[\"116\",\"114\",\"112\",\"108\",\"107\",\"104\",\"102\"]}";

            var arr = JsonConvert.DeserializeObject<Ticket>(json);

            Console.WriteLine(string.Join(';', arr.TicketID));
            Console.ReadLine();
        }

        public class Ticket
        {
            public string[] TicketID { get; set; }  
        }

    }
}
    
22.12.2017 / 19:28
2

Good already given a solution with a type, but, I'll also propose a response, in fact can be done with a structure that already exists which is the Dictionary ( which represents a collection of keys and values ) and also without installing any additional packages since in the JavaScriptSerializer that is included in your question, example :

string json = "{\"TicketID\":[\"116\",\"114\",\"112\",\"108\",\"107\",\"104\",\"102\"]}";

JavaScriptSerializer js = new JavaScriptSerializer();

Dictionary<string, string[]> o = js.Deserialize<Dictionary<string, string[]>>(json);

string[] items = o["TicketID"] as string[]; // todos os valores

22.12.2017 / 19:57