36

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
  • 25,431
  • 32
  • 84
  • 131
  • Your string doesn't have to be an array, it could also be a hash. And an array of what? What does your string look like and what do you want the result to be? What are you trying to achieve. – Tomas Jansson Mar 06 '12 at 15:27
  • possible duplicate of [Parse JSON in C#](http://stackoverflow.com/questions/1212344/parse-json-in-c-sharp) – Oskar Kjellin Mar 06 '12 at 15:27

5 Answers5

68

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.

Icarus
  • 63,293
  • 14
  • 100
  • 115
  • Thanks! Do you know what namespace JavascriptSerializer uses? Getting the 'could not be found' error. – Joey Morani Mar 06 '12 at 15:50
  • 1
    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. – Icarus Mar 06 '12 at 15:52
  • 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. :) – Joey Morani Mar 06 '12 at 16:09
  • @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 – Icarus Mar 06 '12 at 16:10
  • 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. – Alan M Dec 04 '13 at 01:26
11
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);
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Jevgenij Kononov
  • 1,210
  • 16
  • 11
7

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);
ken2k
  • 48,145
  • 10
  • 116
  • 176
5

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; }
        }
    }
}
Kevin Brydon
  • 12,524
  • 8
  • 46
  • 76
2

One Situation that wasn't covered in the other responses is when you don't know the type of what the JSON object contains. That was my case as I needed to be able to NOT type it and leave it dynamic.

var objectWithFields =  js.Deserialize<dynamic[]>(json);

Note: it is definitely preferred to have a type, in some cases, it is not possible, that's why I added this answer.

Meddah Abdallah
  • 654
  • 1
  • 7
  • 25