简体   繁体   中英

C# Json to custom class

I have json:

[
     {
        "Name" : "SHA of timestamp",
        "ProjectURL" : "URL to Proj",
        "AccountIdentifier" : "Account Identifier",
        "Repositories":
        {
            "GitLink1": 
            {
                "Login" : "login1",
                "Password"  : "pas1"
            },
            "GitLink2": 
            {
                "Login" : "login2",
                "Password"  : "pas2"
            },  

            ...

            "GitLink999":
            {
                "Login" : "login999",
                "Password" : "pass999"
            }
        }
    },

    ...

    {
        Same entry
    }
]

I need to fill it in IEnumerable of my created classes

public class Git
{
    public string Login { get; set; }
    public string Password { get; set; }
}

public class Repositories
{
    public Git git { get; set; }
}

public class ConfigEntry
{
    public string Name { get; set; }
    public string ProjectURL { get; set; }
    public string AccountIdentifier { get; set; }
    public Repositories Repositories { get; set; }
}

Using

IEnumerable<ConfigurationEntry> config = JsonConvert.DeserializeObject<IEnumerable<ConfigurationEntry>>(CONFIGJSON);

Where CONFIGJSON contains frst json file.

Gives me this data of ConfigEntry class :

Name : "filled with some data"

ProjectURL : same

AccountIdentifier : same

Repositories : NULL

How i can fill Repositories field with all data i have in config JSON?

Is there any ideas.

It looks like you probably shouldn't have a Repositories class - instead, change your ConfigEntry.Repositories property to:

public Dictionary<string, Git> Repositories { get; set; }

Then you'll get a dictionary where the key of "GetLink1" has a value with Login of "login1" etc.

Your class definitions aren't quite right.

Your "repositories" class only contains a single Git, but needs to be a Dictionary.

I think if you use this you will be close:

public class Git
{
    public string Login { get; set; }
    public string Password { get; set; }
}
public class ConfigEntry
{
    public string Name { get; set; }
    public string ProjectURL { get; set; }
    public string AccountIdentifier { get; set; }
    public Dictionary<string,Git> Repositories { get; set; }
}

you may also need a non-generic IEnumerable, so it knows which objects to actually create:

JsonConvert.DeserializeObject<List<ConfigurationEntry>>(CONFIGJSON);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM