0

I need the data back from the server will be with "data" property, and what JsonConvert.SerializeObject() return is without. How can I convert it?

From:

{
    "name": "Tiger Nixon",
    "position": "System Architect",
    "salary": "$320,800",
    "start_date": "2011/04/25",
    "office": "Edinburgh",
    "extn": "5421"
}

To:

{
    "data": [{
        "name": "Tiger Nixon",
        "position": "System Architect",
        "salary": "$320,800",
        "start_date": "2011/04/25",
        "office": "Edinburgh",
        "extn": "5421"
    }]
}

In VB.net (can be in C# too and I will convert).

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Ballon Ura
  • 882
  • 1
  • 13
  • 36
  • 1
    Simply put your object in array before `JsonConvert.SerializeObject()` – codtex Jul 28 '17 at 09:47
  • https://stackoverflow.com/questions/26795643/how-to-convert-object-containing-objects-into-array-of-objects This might help –  Jul 28 '17 at 09:49

2 Answers2

1

You can parse it to an array and then serialize that back like

Model[] data = JObject.Parse(json_string).ToObject<Model[]>();

Considering you have a model associated to your JSON string

public class Model
{
    public string name { get; set; }
    public string position { get; set; }
    public string salary { get; set; }
    public string start_date { get; set; }
    public string office { get; set; }
    public string extn { get; set; }
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • still not get the "name" propery. now its looks like this: [{"status":2,"transactionId":12345,"creditCardNumber":"1234324324","supplier":"Office Depot","createdAt":"2008-12-28T00:00:00","amount":500.0}] – Ballon Ura Jul 28 '17 at 13:41
1

If you're starting with an instance of your model class, you can just wrap it in an anonymous object and serialize that:

Dim anon = New With {.data = New List(Of Model) From {model}}
Dim json As String = JsonConvert.SerializeObject(anon, Formatting.Indented)

Fiddle: https://dotnetfiddle.net/45RtrC


If you're starting with a JSON string, you can transform it using a JObject:

Dim jo As JObject = JObject.Parse(json)
jo = New JObject(New JProperty("data", New JArray(jo)))
json = jo.ToString()

Fiddle: https://dotnetfiddle.net/ezP6QR

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300