0

I would like to create a JSON proto3 compliant string including a section like this:

"foo": [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]

I can't figure out how to do it. This seems to be a List<List<T>> problem (that has been discussed) but when I feed such a solution to Newtonsoft Json.NET I get:

"foo": [ "bar": [1.0, 2.0], "bar": [3.0, 4.0], "bar": [5.0, 6.0]]

I tried only "Newtonsoft Json.NET" but the question is open to any other JSON libraries or custom coding methods. How can this be done?

EDIT: This is a serialization problem. I have no control over the deserializer code.

2 Answers 2

2

I'm not sure where you're going wrong but the following code works perfectly fine:

var lists = new List<List<double>>
{
    new List<double> {1.0, 2.0},
    new List<double> {3.0, 4.0}
};
var test = (lists, "test");
Console.Write(JsonConvert.SerializeObject(test));

Output:

{"Item1":[[1.0,2.0],[3.0,4.0]],"Item2":"test"}

Could you edit your post with some sample code?

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

1 Comment

Actually this looks very good. Give me the rest of Valentine's Day and I will confirm ASAP.
1

Try this:

string str = "{ \"foo\": [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]] }";
var mytype = new { foo = new List<List<decimal>>() };
var mydeserializedtype = JsonConvert.DeserializeAnonymousType(str, mytype);
string str2 = JsonConvert.SerializeObject(mydeserializedtype);

or more classic

class myclass
{
 public List<List<decimal>> foo { get; set; }
}
….
string str = "{ \"foo\": [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]] }";
myclass my = JsonConvert.DeserializeObject<myclass>(str);
string str2 = JsonConvert.SerializeObject(my);

2 Comments

Ehm, actually I would like to serialize and not to deserialize. I thought I made it clear, nevertheless I will edit.
deserializeis the exact opoposite of deserialize. It means that if you find the class that will result the deserialize, you know what object to instancite in order to produce the right serialize. This answer show you this concept by deserialize str into my then deserialize my into str2. Poor choice or var name but still a clear path to the solution. The only answer of how to serialize that is to learn how to deserialize, this make all question about serialisation duplicate of how to deserialize in my eyes.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.