I'm trying to convert a string with JSON data to an array.
I'm using NewtonSoft.JSON
The following line of code holds my JSON data in a string:
string jsonString = manage.getData();
I've tried the following:
name[] result = JsonConvert.DeserializeObject<name[]>(jsonString);
string name = result.Name;
Name class:
using System;
namespace Zoekfunctie {
public class name {
public string Name {get;set;}
public string Id { get; set; }
}
}
So how can I convert my JSON string to an array of strings?
JSON string: [{"id":"42","naam":"Bas Jansen"},{"id":"41","naam":"Bas Jansen"}]
You just need to call DeserializeObject
providing the array type instead of the single class type. Here's a short but complete program demonstrating this... I've adjusted your JSON and class to match each other.
using System;
using System.IO;
using Newtonsoft.Json;
public class Person
{
public string Id { get; set; }
public string Name {get;set;}
}
class Program
{
static void Main(string[] args)
{
string text = "[{\"id\":\"42\",\"Name\":\"Bas Jansen\"},{\"id\":\"41\",\"Name\":\"Bas Jansen\"}]";
var array = JsonConvert.DeserializeObject<Person[]>(text);
Console.WriteLine(array.Length);
Console.WriteLine(array[0].Id);
}
}
See more on this question at Stackoverflow