Fueled By Coffee
Fueled By Coffee

Reputation: 2569

JsonConvert SerializeObject not correctly serializing String Array

I'm posting some JSON to a REST server using the following RestConnector:

using Newtonsoft.Json;

public static T httpPost(String myURL, Dictionary<string, string> data) {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myURL);
    Console.WriteLine("Sending Request to: " + myURL);

    request.Method = "POST";

    var json = JsonConvert.SerializeObject(data);


    Console.WriteLine("");
    Console.WriteLine("");
    Console.WriteLine("JSON: "+ json);
    Console.WriteLine("");
    Console.WriteLine("");

    ASCIIEncoding encoding = new ASCIIEncoding();
    byte[] byte1 = encoding.GetBytes(json);
    request.ContentType = "application/json";
    request.ContentLength = byte1.Length;

    Stream newStream = request.GetRequestStream();
    newStream.Write(byte1, 0, byte1.Length);
    newStream.Close();
    //...
}

I'm getting the following error back from the server*:

Can not deserialize instance of java.lang.String[] out of VALUE_STRING

Upon further investigation, this is the raw JSON that's being posted:

{
    "tag1":"val1",
    "tag2":"System.String[]", 
    ...
}

How can I serialize this object so that the array is sent properly?

Example:

{
    "tag1":"val1",
    "tag2":[],
    ...
}

EDIT:

This is where I create the object that I'm serializing:

    MyObject mo =new MyObject();
    mo.tag1= "val1";
    mo.tag2= new String[]{};

    Dictionary<string, string> input = objectToDictionary(mo);

    mo = RestConnector<MyObject>.httpPost("http://example.com", input);

objectToDictionary

 public Dictionary<string, string> objectToDictionary(object obj) {
     return obj.GetType().GetProperties()
         .ToDictionary(x => x.Name, x => x.GetValue(obj)?.ToString() ?? "");
 }

Upvotes: 1

Views: 2592

Answers (1)

Gimly
Gimly

Reputation: 6175

Your issue is in your objectToDictionary method, the ToString implementation for an array of string simply returns "System.String[]".

You have to change your implementation so that Json.Net receives the string array directly, he'll figure out how to serialize it.

Upvotes: 1

Related Questions