Search code examples
javac#jsonjson.net

how to deserialize a custom json to c# object


I use Newtonsoft.json to deserialize this json

{
    "pdf_info": [
        [
         -> this is a object {
           "order_serial_no": "xxxxx",
           // more properties
         },
        -> this is an array ["xxxx", "x"]
        ]
    ]
}

In java I can use the following code to achieve this.

JSONArray pdfArray = JSONArray.parseArray(pdf_info);
String pdfArrayOne = pdfArray.getString(0);
JSONArray jsonArray = JSONObject.parseObject(pdfArrayOne, JSONArray.class);
String jsonData = jsonArray.getString(0);
Pdf pdf = JSONObject.parseObject(jsonData, Pdf.class);

So, how to deserialize this json with newtonsoft.json


Solution

  • Apparently (after removing your comments) this would be the c# class of your object (Copy the json to clipboard -> in Visual Studio 'Edit->paste special->paste json as class' - see more on this)

    public class Rootobject
    {
      public object[][] pdf_info { get; set; }
    }
    

    Define this Type and you would be able to deserialize it using:

    Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(System.IO.File.ReadAllText(fileName));