0

I can't seem to wrap my head around JSON in C#. I use JSON.NET and usually I can figure out the class needed to convert. However in this case it's challenging: there is no name for the individual list items.

{"error":[], "result":{"currency":[[2.0, 3.0, 4.0, 5.0], [6.0, 7.0, 8.0, 9.0], ... ]}}

This is an example from memory, I hope the syntax is right.

So, when I attempt to create the classes, I don't know where to start. Say, I am interested in the result pair. Is "currency" a list of lists? How would I map the value for the list (2.0, 3.0, 4.0, 5.0) and its enclosing result?

Not sure at all...

1
  • 1
    Why not use a website converter like JSON2C#? Commented Sep 17, 2016 at 0:54

2 Answers 2

1

Currency is a list of lists of double. Your Result object should look something like:

public class Result {
    List<List<double>> Currency {get;set;}
}

Additionally, Visual Studio has a 'Paste Special' option under the Edit Menu that can be used to turn an XML or JSON string from the clipboard into C# classes that conform to the structure.

Sign up to request clarification or add additional context in comments.

4 Comments

Ah, that makes more sense now. But since the doubles don't have a name, I would end up with a (hopefully) ordered List. How would you assign the values (in the right order) to custom variables in the class?
I would recommend that any business logic level mapping be done outside of parsing the JSON object. Just because those values appear in groups of 4 in most cases doesn't give an guarantee that they would always do so, and it will typically be easier to determine the source of a mapping issue than a parsing one.
So you would advise to map the JSON object as-is and process the data in a method later? How would I guarantee which values I am attempting to put into variables? Is the List ordered in the way the JSON provides so I can use array notation or LINQ?
I can't say anything definitively about the list. I would expect it to be ordered the same way the json is ordered. It would depend on your business rules and needs with the data to determine how you would process it.
1

To avoid any probability of errors, you can do like this: copy your JSON file, go to Visual Studio=>Edit=>Paste Special=>Paste JSON as class. This will generate the classes for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.