Deserialize Json string[] for string[]

Asked

Viewed 167 times

4

I have the following JSON:

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

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

Server Error in Application '/'.

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

Exception Details: System.Missingmethodexception: No constructor no parameters set for 'System.String type[]'.

Error of Origin:

Line 130: //Return 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 solved the problem.

How to extract a string[] that JSON?

2 answers

3


Using the Newtonsoft.Json library which is one of the most widely 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; }  
        }

    }
}

2

Good already given a solution with a type, but, I will also propose an answer, actually can be done with a structure that already exists which is the Dictionary (representing a collection of keys and values) and also without installation of any additional package since in the has an implementation for such Javascriptserializer that is even 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

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.