-1

So I'm making an app and I need to extract data from JSON files dynamically.

Here is a snippet of the JSON file:

{
    "004bb5ee-34ba-484a-924b-31412d898e7e": {
        "title": "obj_survivalobject_elevatordoor_left"
    },
    "00284190-1484-4286-a198-b2ddef768c2e": {
        "description": "Adds shock absorption and provides stability. Great for vehicles to prevent them from easily flipping over. This suspension has a lot of bounce, making it ideal for off-road vehicles.",
        "title": "Off-Road Suspension 2"
    },
    "011c1ffd-7146-4e8d-8c18-17247d768ae2": {
        "title": "obj_spaceship_wall04"
    }
}

There is lots more in the file. But I only need to get the title and the parent of that title. Eg:

Tag: "00284190-1484-4286-a198-b2ddef768c2e"
Name: "Off-Road Suspension 2"

I don't want the description and not all have one.

I will also be using JSON files that are selected by the user while the application is running.

Redstone145
  • 103
  • 2
  • 8
  • 2
    Have you ever deserialized json before? Is there any reason why you haven't tried to deserialise this to a `Dictionary` and pick the results from that ? – TheGeneral Sep 06 '21 at 01:12
  • Does this answer your question? [json deserialization to C#](https://stackoverflow.com/questions/65727513/json-deserialization-to-c-sharp) – Charlieface Sep 06 '21 at 01:47

2 Answers2

2

try this

var jsonDeserialized = JsonConvert.DeserializeObject<Dictionary<string,Description>>(json); 
var list = jsonDeserialized.Select(kvp => new TagName { Tag = kvp.Key, 
Name=kvp.Value.title} ).ToList();

var output = JsonConvert.SerializeObject(list);

output

[{"Tag":"004bb5ee-34ba-484a-924b-31412d898e7e","Name":"obj_survivalobject_elevatordoor_left"},
{"Tag":"00284190-1484-4286-a198-b2ddef768c2e","Name":"Off-Road Suspension 2"},
{"Tag":"011c1ffd-7146-4e8d-8c18-17247d768ae2","Name":"obj_spaceship_wall04"}]

or this way

foreach (var item in list)
{
     Console.WriteLine ( $"Tag : {item.Tag}, Name: {item.Name}");
        
}

classes

public class Description
{
    public string description { get; set; }
    public string title { get; set; }
}

public class TagName
{
    public string Tag { get; set; }
    public string Name { get; set; }
}
Serge
  • 40,935
  • 4
  • 18
  • 45
0

Try deserializing your Json file into a collection (list/dict/etc).

See here for details about Serializing and Deserializing in C#.