Convert json to a C# array?

202,278

Solution 1

just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

You'd need to create a C# class called, for example, Person defined as so:

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

You can now deserialize the JSON string into an array of Person by doing:

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

Here's a link to JavaScriptSerializer documentation.

Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.

Solution 2

using Newtonsoft.Json;

Install this class in package console This class works fine in all .NET Versions, for example in my project: I have DNX 4.5.1 and DNX CORE 5.0 and everything works.

Firstly before JSON deserialization, you need to declare a class to read normally and store some data somewhere This is my class:

public class ToDoItem
{
    public string text { get; set; }
    public string complete { get; set; }
    public string delete { get; set; }
    public string username { get; set; }
    public string user_password { get; set; }
    public string eventID { get; set; }
}

In HttpContent section where you requesting data by GET request for example:

HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync();
//deserialization in items
ToDoItem[] items = JsonConvert.DeserializeObject<ToDoItem[]>(mycontent);

Solution 3

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

Solution 4

Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}
Share:
202,278
Joey Morani
Author by

Joey Morani

Updated on February 03, 2022

Comments

  • Joey Morani
    Joey Morani over 2 years

    Does anyone know how to convert a string which contains json into a C# array. I have this which reads the text/json from a webBrowser and stores it into a string.

    string docText = webBrowser1.Document.Body.InnerText;
    

    Just need to somehow change that json string into an array. Been looking at Json.NET but I'm not sure if that's what I need, as I don't want to change an array into json; but the other way around. Thanks for the help!

  • Joey Morani
    Joey Morani about 12 years
    Thanks! Do you know what namespace JavascriptSerializer uses? Getting the 'could not be found' error.
  • Icarus
    Icarus about 12 years
    Yes, it's on the documentation I linked. It's in System.Web.Script.Serialization. You need to add a reference to the System.Web.Extensions assembly.
  • Joey Morani
    Joey Morani about 12 years
    Ah, thanks. Got it working. Think it's 'JavaScriptSerializer' not 'JavascriptSerializer' though. That's why I was getting that error. You might want to edit that. :)
  • Icarus
    Icarus about 12 years
    @JoeyMorani Sorry about that. I will edit it. Of course, when I test it locally, VS corrected for me and I didn't realize it. :S
  • Alan M
    Alan M over 10 years
    Thank you for a very simple solution to what should be, and turns out to be, a sipmle problem. The other solutions seemed to burn up dozens of lines of code, and I couldn't get 'em to work.