Joe Scotto
Joe Scotto

Reputation: 10877

How to use an array in json.net

How would I pass an array into JsonConvert.SerializeObject? I have the following working JSON but am unable to get it into the serialize function because it needs an array.

"recipients": [
    { 
        "address": "[email protected]" 
    },
    { 
        "address": "[email protected]" 
    },
    { 
        "address": "[email protected]" 
    }   
]

I'm new to c# and any help would be great, thanks!

C# body:

 recipients = new Array {

                }

Upvotes: 1

Views: 390

Answers (2)

goodfellow
goodfellow

Reputation: 3735

Great way to create c# classes from JSON is http://json2csharp.com/. When I wrapped your JSON into curly braces as @dbc suggested and pasted there following code was generated:

public class Recipient
{
    public string address { get; set; }
}

public class RootObject
{
    public List<Recipient> recipients { get; set; }
}

Now you can deserialize it like this:

RootObject myObject = JsonConvert.DeserializeObject<RootObject>(myJSON);

Upvotes: 2

BetterLateThanNever
BetterLateThanNever

Reputation: 906

In order to build a valid Json object, Please refer to http://json.org/

For below model,

public class Model
{
    public string[] recipients { get; set; }
}

with below JsonDocument,

string jsondoc = "{\"recipients\": [\"[email protected]\",\"[email protected]\",\"[email protected]\"]}"

Below piece of code shoule be able to deserialize your json document

Model obj = new Model();
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsondoc)))
{
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Model));
    obj = (Model)deserializer.ReadObject(ms);
}

Upvotes: 0

Related Questions