1

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 {

                }
6
  • 2
    That's not valid JSON. It is missing outer braces -- { and }. Is that a typo in the question? Commented Apr 13, 2017 at 18:46
  • You also haven't specified what your target structure looks like. Also, I assume you've made a mistake and what you mean to say is you are trying to deserialize your json, not serialize it, since you haven't shown an origin C# object. Commented Apr 13, 2017 at 18:49
  • @dbc That's just a portion of my request. Commented Apr 13, 2017 at 18:51
  • codeproject.com/Tips/79435/Deserialize-JSON-with-C Commented Apr 13, 2017 at 19:03
  • github.com/fxstar/connectAPI/tree/master/Json Commented Apr 13, 2017 at 19:07

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

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.