1

I need to serialize an object with Newtonsoft JSON, desired output:

[  
   [[1, 2, "15"],[3, 4, "12"]]
]

My class:

 public class Result
 {
  public int? score1;  
  public int? score2;    
  public string id;
 }

Id has to be of a string type. After converting to JSON:

string json = JsonConvert.SerializeObject(myObject);

I, quite logically get this:

[  
   [  
      {  
         "score1":null,
         "score2":null,
         "id":"5824"
      },
      {  
         "score1":null,
         "score2":null,
         "id":"5825"
      }
   ],
   [next object]
]
Matěj Štágl
  • 870
  • 1
  • 9
  • 27
  • 1
    You don't say the type of `myObject`. Assuming it's a collection of collections of `Result`, you can use `ObjectToArrayConverter` from [C# JSON.NET - Deserialize response that uses an unusual data structure](https://stackoverflow.com/a/39462464/3744182). In fact I think this is a duplicate, agree? – dbc Mar 16 '19 at 17:08
  • @dbc thanks for helping me out, this worked like a charm. Since you are the one who's around for a while I'm leaving decision to you. On the other hand this question might be a good entry search point for other users. – Matěj Štágl Mar 16 '19 at 17:15
  • 1
    *this question might be a good entry search point for other users.* closing as a duplicate doesn't mean the question gets deleted, it means that the duplicate appears at the top, and anonymous readers are redirected to the original question when the duplicate has no answers. – dbc Mar 17 '19 at 16:50
  • Thanks for your kind explanation. Agreed. – Matěj Štágl Mar 17 '19 at 18:37

1 Answers1

4

You can try with the JProperties.Values() method to extract the values and serialize it finally using JSON.NET:


public class Program
{
    public static void Main(string[] args)
    {
        List<Result> resultList = new List<Result>
        {
            new Result 
            {
                score1 = 1,
                score2 = 2,
                id = "15"
            },
            new Result
            {
                score1 = 3,
                score2 = 4,
                id = "12"
            }
        };




        var valuesList = JArray.FromObject(resultList).Select(x => x.Values().ToList()).ToList();

        string finalRes = JsonConvert.SerializeObject(valuesList, Formatting.Indented);

        Console.WriteLine(finalRes);
    }
}

public class Result
{
     public int? score1 {get; set; }
     public int? score2 { get; set; }   
     public string id { get; set; }
}

Giving results:

[
  [
    1,
    2,
    "15"
  ],
  [
    3,
    4,
    "12"
  ]
]
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53
  • 1
    Thanks Kunal, I just got it working with suggested approach from dbc but I am pretty sure this one is nice too. Accepted. – Matěj Štágl Mar 16 '19 at 17:17