1

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;
        }
    }
}
?>
9
  • Do you have control over the JSON? Because your JSON isn't an array of objects. Commented Jul 28, 2020 at 13:32
  • Yes, I do, but it's written in PHP so I'm not so sure how :/ Do you think I will have to change my whole json for it to be "compatible" with C#? Commented Jul 28, 2020 at 13:33
  • 1
    app.quicktype.io?share=QBtI4DtpYJoYv5y3ytsw Commented Jul 28, 2020 at 13:35
  • 1
    you would be better off fixing your JSON. Can you post the PHP code that generates this? Commented Jul 28, 2020 at 13:37
  • 1
    you are building an associative array when there is really no need for it. Instead just build a simple array of data, then return the json for that array Commented Jul 28, 2020 at 13:49

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

Comments

1

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);
}

2 Comments

Assuming there is some reason the OP would want an object that is nothing but an array of other objects. This is a code smell to me, without there being something else useful in the parent class, especially with a name of "Ids" that isn't something like Int64.
I'm confident the OP has to potential to figure out better namings for properties depending on the scope of his use-case. That's not what this anwser is aiming for.
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.