user3357400
user3357400

Reputation: 397

write data from JSON in C#

I have JSON like this:

{
    'surveys': [
        {
            'title': 'first',
            'id': 100,
        },
        {
            'title': 'second',
            'id': 101,
        },
        {
            'title': 'third',
            'id': 102,
        },
    ]
}

I want to have the output like this:

title: first
title: second
title: third

and my program in C# is like this:

WebClient client = new WebClient();
var json = client.DownloadString("http://www.test.com/api/surveys/?api_key=123");
Debug.WriteLine(json); //write all data from json

//add
var example = JsonConvert.DeserializeObject<Example>(json);
Debug.WriteLine(example.Data.Length);

class Example
{
    public surveys[] Data { get; set; }
}

class surveys
{
    public string title { get; set; }
    public int id { get; set; }
}

I get this error:

Thrown: "Object reference not set to an instance of an object." (System.NullReferenceException) Exception Message = "Object reference not set to an instance of an object.", Exception Type = "System.NullReferenceException", Exception WinRT Data = ""

at this line: Debug.WriteLine(example.Data.Length);

where is the problem?

Upvotes: 0

Views: 229

Answers (4)

Jon Bates
Jon Bates

Reputation: 3173

One problem I see is that your outer class has a property named Data, which is an array of 'surveys' objects, but your Json has a list of 'surverys' objects under the property 'surveys'. Hence the 'Data' property is never populated.

Consider the following C# class structure:

class Example
{
    public survey[] surveys{ get; set; }//Data renames to surveys
}

class survey //Singular
{
    public string title { get; set; }
    public int id { get; set; }
}

Upvotes: 1

Antoine Cloutier
Antoine Cloutier

Reputation: 1330

Use json2csharp to generate c# classes from json. You will also need to use Json.NET.

public class Survey
{
    public string title { get; set; }
    public int id { get; set; }
}

public class RootObject
{
    public List<Survey> surveys { get; set; }
}

Then you can do:

var client = new WebClient();
string json = client.DownloadString(some_url);

RootObject root = JsonConvert.DeserializeObject<RootObject>(json);

foreach (Survey s in root.surveys)
{
    // Do something with your survey
}

Don't forget to use Newtonsoft.Json namespace once you add a reference to it within your project.

using Newtonsoft.Json;

Edit: I have tested it using:

string json = "{'surveys': [{'title': 'first','id': 100,},{'title': 'second','id': 101,},{'title': 'third','id': 102,},]}";

instead of using the WebClient, and it works.

Upvotes: 1

Callum Linington
Callum Linington

Reputation: 14417

You need to use JSON.Net and use the class JsonConvert and the method DeserializeObject<T>.

If you run this:

JsonConvert.DeserializeObject<JObject>();

Then you will get back a list of de-serialized JObject objects.

Use, NuGet to download the package. I think it is called JSON.net.

Here is the weblink

WebClient client = new WebClient();
var json = client.DownloadString("http://www.test.com/api/surveys/?api_key=123");
Debug.WriteLine(json); //write all data from json

//add
var example = JsonConvert.DeserializeObject<Survey>(json);
Debug.WriteLine(example.length); // this could be count() instead.

class Survey
{
    public string title { get; set; }
    public int id { get; set; }
}

This should work!

Upvotes: 1

Igor Tkachenko
Igor Tkachenko

Reputation: 1120

Why can't you do so?:

JObject data = JObject.Parse(json);
foreach (var survey in data["surveys"].Children())
{
    Debug.WriteLine("title: " + survey["title"]);
}

Upvotes: 1

Related Questions