user11745417
user11745417

Reputation:

How to iterate JSON in C# and add every object to List?

I have a JSON in this format:

{
  "id1": {
    "id": "183",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-27"
  },
  "id2": {
    "id": "182",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-23"
  },
  "id3": {
    "id": "180",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-20"
  },
  "id4": {
    "id": "179",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-19"
  }
}

I need to loop through it and add every item to new ArrayList:

ArrayList NewList = new ArrayList();

I need it so I can loop through my ArrayList later and retrieve any object I want. I tried using this website https://json2csharp.com/, but it returns this:

public class Id1    {
    public string id { get; set; } 
    public string contentname { get; set; } 
    public string content { get; set; } 
    public string created { get; set; } 
}

public class Id2    {
    public string id { get; set; }  
    public string contentname { get; set; } 
    public string content { get; set; } 
    public string created { get; set; } 
}

public class Root    {
    public Id1 id1 { get; set; } 
    public Id2 id2 { get; set; } 
}

That is not very useful to me, because there will be 100+ different ids and more are added every day.

Is there any way to do what I want? It's for my Xamarin project, in Android I used Volley library and it works great, but I keep struggling in C#.

Thanks for help :)

EDIT: This is the PHP that generates my json:

<?php
class SeznamNovinekApi extends BaseApi
{
    public function ToProcess($parametry)
    {
        $novinkyInfo = Database::SqlGetFetchAll("select id, pageid, contentname, content, created from mainpagesarticles where pageid = ? order by created desc", array('novinky'));

        $i = 0;
        foreach ($novinkyInfo as $info)
        {
            $i++;
            $obj = ["id" => $info["id"], "pageid" => $info["pageid"], "contentname" => $info["contentname"], "content" => $info["content"], "created" => $info["created"]];
            $this->json['id' . $i] = $obj;
        }
    }
}
?>

Upvotes: 1

Views: 1943

Answers (4)

Alexander Petrov
Alexander Petrov

Reputation: 14231

I used exactly your json.

Create model:

public class Data
{
    public int Id { get; set; }
    public string ContentName { get; set; }
    public string Content { get; set; }
    public DateTime Created { get; set; }
}

Open namespace:

using Newtonsoft.Json.Linq;

Use this code:

var text = File.ReadAllText("test.json");
var json = JObject.Parse(text);
var list = new List<Data>();

foreach (var prop in json.Properties())
{
    var value = prop.Value;
    var data = new Data
    {
        Id = value["id"].Value<int>(),
        ContentName = value["contentname"].ToString(),
        Content = value["content"].ToString(),
        Created = value["created"].Value<DateTime>()
    };
    list.Add(data);
}

Upvotes: 1

user11745417
user11745417

Reputation:

Thank you so much to every one who responded, for now the Quicktype code from mjwills works, but I will probably just fix my json instead and do it properly :) thanks!

Upvotes: 0

Thomas Luijken
Thomas Luijken

Reputation: 645

Going by the comments below your question, and seeing you have the ability to fix your Json I would suggest you fix your JSON first into something like this (which has an actual array of id elements).

{
  "ids": [
    {
      "id": "183",
      "contentname": "Title",
      "content": "Some text",
      "created": "2020-07-27"
    },
    {
      "id": "182",
      "contentname": "Title",
      "content": "Some text",
      "created": "2020-07-23"
    },
    {
      "id": "180",
      "contentname": "Title",
      "content": "Some text",
      "created": "2020-07-20"
    },
    {
      "id": "179",
      "contentname": "Title",
      "content": "Some text",
      "created": "2020-07-19"
    }
  ]
}

Once you have that in order, there is a very nifty tool in visual studio to help you with constructing class definitions based on this JSON. Copy the json to your clipboard and to to: Edit -> Paste Special -> Paste JSON as classes. You can this this while having a *.cs file open.

This will construct the following JSON for you.

public class Ids
{
    public Id[] ids { get; set; }
}

public class Id
{
    public string id { get; set; }
    public string contentname { get; set; }
    public string content { get; set; }
    public string created { get; set; }
}

After that, the process is pretty straight forward:

private static void Main(string[] args)
{
    var json = File.ReadAllText("test.json");
    var ids = JsonSerializer.Deserialize<Ids>(json);
    Console.WriteLine(ids);
}

Upvotes: 1

Austin T French
Austin T French

Reputation: 5131

Ideally, your JSON should look more like this:

{[
  {
    "id": "183",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-27"
  },
  {
    "id": "182",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-23"
  },
  {
    "id": "180",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-20"
  },
  {
    "id": "179",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-19"
  }
]}

Just plain array of JSON objects. You don't need an outer identifier, but you do want an Array. Your previous JSON was a single object with many child objects.

With this, (and pseudo code) any JSON converter would essentially work like:

MyType[] arrayOfObjects = JSON.Convert<MyType>(myJson);

Upvotes: 2

Related Questions