Parsing JSON
I'm struggling to parse and iterate over a JSON array of "key/object" elements. For instance, something in this format:
Using Netwonsoft for JSON parsing.
30 Replies
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
There's no code to show
I have iteration and such, I'm just struggling on the one line to parse that JSON string into an object
Y'know, something along this line
var obj = JsonConvert.DeserializeObject<>(input);
But I can't figure out what to put as the type for that to parseYou need to create a class which models your JSON structure
I didn't want to do that, ideally doing this without the need of that
Figured it out anyways,
Dictionary<string, dynamic>
did the trickWhy?
Because why have another class when it's unneeded
Do not use
dynamic
. Ever.One less thing to worry about
Why not?
DO NOT USE DYNAMIC
I've never used it before
C# is a statically typed language which means that every property of every class is available at compile-time.
dynamic
just skids around that and says fuck you to the compiler and allows you to access random things at runtime. This might seem great, but it comes at firstly a pretty major performance cost, and secondly the cost of not being able to navigate through your JSON structure safely.dynamic solves some corner cases, but should be avoided
Gotcha
I guess I'll make a class then
You are much better off going through the trouble of just creating a class modelling your JSON structure. If you're using VS it even has a tool for this, and there are online tools for generating this.
if you don't make a class you're always going to be tunneling through to get config
I know how, I was just trying to see if there was an alternative
environment variables
but you'll not want to use those directly either
Actually, even making a class, I'm not sure how I'd deserialize this
Assume that within a key there's potential for there to be more than 1 param
I was thinking it'd be like
string, obj
kinda thingyou're using newtonsoft?
Yeah
var myconfig = JsonConvert.DeserializeObject<MyConfig>(someJsonStriing);
I know that, the
MyConfig
part is the part I'm struggling on
I sent a sample of what I'm trying to parse aboveCould be a dictionary of dictionaries, could be a class with dictionaries, could be a dictionary of classes, could be a class with classes
Depends on if, and if so which, keys are always the same or dynamic
Keys are dynamic
Eh I might just make this an array and put the key in the obj
It's kinda pointless doing what I'm doing for my purposes
A dictionary of dictionaries, then
Or of classes
I'm just gonna make it an array
It won't deserialize to an array, since you have the keys there
At least I don't think it will
I'm changing the json format
Haven't used Newtonsoft in ages, so can't tell
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View