0
{
  Items: [
    {
      "title": "Object1",
      "preview": {
        "2048": "preview_9212.jpg",
        "1024": "preview_6693.jpg",
      }
    },
    {
      "title": "Object2",
      "preview": {
        "2048": "preview_9888.jpg",
        "1024": "preview_6890.jpg",
      }
    },
    {
      "title": "Object3",
      "preview": {
        "2048": "preview_9822.jpg",
        "1024": "preview_6848.jpg",
      }
    }
  ]
}

I usually deserialise like this:

[Serializable]
public class JsonParser
{
    public string title;
    public List<Preview> preview;
}

[Serializable]
class Preview
{
    public string 2048;
} 

But since 2048 is an Integer is not possible to use this way. I tried to deserialize the JSON to get preview like these:

public class Preview
{
  [JsonProperty("2048")]
  public string imageNumber { get; set; }
}

var user = JsonConvert.DeserializeObject<Preview>(jsonValue);

or

var json = JObject.Parse(jsonValue);
var preview = json["preview"].ToObject<Dictionary<string, string>>();
foreach (var entry in preview)
{
    Debug.Log(entry.Key);
    Debug.Log(entry.Value);
}

I got: NullReferenceException: Object reference not set to an instance of an object.

I also tried Deserializing JSON that has an int as a key in C# but again NullReferenceException;

Thanks for any help!

A9191
  • 23
  • 5
  • The JsonProperty attribute doesn't do what you think it does. You need to deserialize the whole thing, and then get the data you want from the deserialized object. – Robert Harvey Feb 08 '22 at 14:49
  • your json string has much more nested levels than your coded types. maybe you can try some **json path**. – Lei Yang Feb 08 '22 at 14:50
  • 1
    Have a look [here](https://stackoverflow.com/questions/37335030/deserialize-part-of-json-string-array-in-c-sharp) and [here](https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm). – Robert Harvey Feb 08 '22 at 14:53
  • @RobertHarvey the problem is on those ones the key is not an Integer. – A9191 Feb 08 '22 at 15:02
  • The key is not an integer in your code and sample either. – Julian Silden Langlo Feb 08 '22 at 15:18
  • if the problem is about int keys, you should paste a much simpler json, e.g. `{"1":"a"}` don't mess up our mind with unrelated things. – Lei Yang Feb 08 '22 at 15:18
  • Thanks for all of your comments! I updated the question. – A9191 Feb 08 '22 at 15:36
  • 2
    The JSON shown is invalid (no quotes around `Items`), and will be difficult to deserialize because of differing property names (two of the objects have `"title"`, one has `"type"`). Please edit your title, as there are no integer keys; there are numeric string keys. Similar problem, different description. – Heretic Monkey Feb 08 '22 at 15:48

1 Answers1

1

Since you have numeric string properties, you have 2 main choices:

  1. Use something like [JsonProperty("2048")] and select valid name for the property

  2. Or use a dictionary. This looks much more flexible for me, so you can try this code

Data data= JsonConvert.DeserializeObject<Data>(json);

string preview2048 = data.Items[0].Preview["2048"];  //preview_9212.jpg

or more complicated search using Linq

string  obj3Preview2048 = data.Items.Where(i=> i.Title == "Object3")
.Select(i =>i.Preview["2048"]).FirstOrDefault(); //preview_9822.jpg

classes

public partial class Data
{
    [JsonProperty("Items")]
    public List<Item> Items { get; set; }
}

public partial class Item
{
    [JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)]
    public string Title { get; set; }

    [JsonProperty("token")]
    public string Token { get; set; }

    [JsonProperty("preview")]
    public Dictionary<string, string> Preview { get; set; }
}

and you have some typos in json you posted, and I fix "type" to "title" in one of json objects. This is a fixed version

{
    "Items": [{
            "title": "Object1",
            "token": "6561b1bbe5f1958848jhgd43d2",
            "preview": {
                "2048": "preview_9212.jpg",
                "1024": "preview_6693.jpg"
            }
        },
        {
            "title": "Object2",
            "token": "4a42eb54648DSFhUI664654d25",
            "preview": {
                "2048": "preview_9888.jpg",
                "1024": "preview_6890.jpg"
            }
        },
        {
            "type": "Object3",
            "token": "3fba64831dghkjgfkl5dfaegoj9",
            "preview": {
                "2048": "preview_9822.jpg",
                "1024": "preview_6848.jpg"
            }
        }
    ]
}
Serge
  • 40,935
  • 4
  • 18
  • 45