ramafe
ramafe

Reputation: 123

JsonConvert help reading from file

I am trying to read from this json file, The problem is that I am not getting any info back, also 1357 is always changing.

This is part of the file

{
    "result": {
        "1357": {
            "Random": "4NUX4oFJZEHLbXH5ApeO4",
            "Random2": "Co04DEVlxkKgpou-6kej",

The class I am using to read it

using System;
using System.IO;
using Newtonsoft.Json;

namespace MyNamespace
{
    public class ReadRandom
    {
        public static ReadRandom Fetch(string filename)
        {
            TextReader reader = new StreamReader(filename);
            string json = reader.ReadToEnd();
            reader.Close();

            ReadRandomResult AssetClassInfoResult = JsonConvert.DeserializeObject<ReadRandomResult>(json);

            return AssetClassInfoResult.result;
        }

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

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


        protected class ReadRandomResult
        {
            public ReadRandom result { get; set; }
        }

    }
}

Errors from one of the answers

Exception thrown: 'System.ArgumentException' in Newtonsoft.Json.dll
Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll
Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll
Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll
Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
Additional information: Exception has been thrown by the target of an invocation.

http://pastebin.com/Hvp4CXXw

Im trying to read "icon_url" An a few things under that. Sorry that i didnt post it all before thought i didnt need it When using that in the example you posted an change the key to the right one i still crash.

Upvotes: 1

Views: 617

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1502296

The problem is that you've got the extra "layer" between the result property and the object with Random and Random2. It looks like you want something like:

class ReadRandomResult
{
    public Dictionary<string, ReadRandom> Result { get; set; }
}

Then you'd be able to use:

var container = JsonConvert.DeserializeObject<ReadRandomResult>(json);
var result = container.Result["1357"];

As a note, I'd strongly recommend moving your ReadRandomResult class outside ReadRandom... it's pretty unusual to have a "container" class nested inside the class it contains. That's likely to cause confusion.

Here's a short but complete example that works:

using System;
using System.Collections.Generic;
using System.IO;

using Newtonsoft.Json;

class ReadRandom
{
    [JsonProperty("Random")]
    public string Random { get; set; }

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

class ReadRandomContainer
{
    [JsonProperty("Result")]
    public Dictionary<string, ReadRandom> Result { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var json = File.ReadAllText("test.json");
        var container = JsonConvert.DeserializeObject<ReadRandomContainer>(json);
        Console.WriteLine(container.Result["1357"].Random);
    }
}

Contents of test.json:

{
    "result": {
        "1357": {
            "Random": "4NUX4oFJZEHLbXH5ApeO4",
            "Random2": "Co04DEVlxkKgpou-6kej"
        }
    }
}

Output:

4NUX4oFJZEHLbXH5ApeO4

Upvotes: 2

jan_kiran
jan_kiran

Reputation: 302

Check this link where the json string has dynamic keys, they are using Idictionary and then iterating over. Deserializing JSON with dynamic keys. Then from the remaining string you can again deserialize to the object what you want

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34234

You ignore the fact that you have 1357. Assuming you have the following JSON:

{
    "result": {
        "1357": {
            "Random": "4NUX4oFJZEHLbXH5ApeO4",
            "Random2": "Co04DEVlxkKgpou-6kej"
        } 
    }
}

your result is not a ReadRandom, but a Dictionary<string, ReadRandom>.

This one should work:

public class ReadRandom
{
    public static Dictionary<string, ReadRandom> Fetch(string filename)
    {
        TextReader reader = new StreamReader(filename);
        string json = reader.ReadToEnd();
        reader.Close();

        return JsonConvert.DeserializeObject<ReadRandomResult>(json).result;
    }

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

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


    protected class ReadRandomResult
    {
        public Dictionary<string, ReadRandom> result { get; set; }
    }
}

// Usage example:
string random = ReadRandom.Fetch(@"C:\filename.txt")["1357"].Random;

Just my opinion: implementing Fetch within a model class isn't a very good idea. It is better to implement something like ReadRandomParse which will return ReadRandomResult.

Upvotes: 0

Niek de Gooijer
Niek de Gooijer

Reputation: 684

The json you posted seems invalid. The parser can't read it.

--- edit:

at minimum you need

{
    "result": {
        "1357": {
            "Random": "4NUX4oFJZEHLbXH5ApeO4",
            "Random2": "Co04DEVlxkKgpou-6kej"
        }
    }
}

Upvotes: 0

Related Questions