0

I'm working with a object in C#.

 public class City
   {
      public int id { get; set; }
      public string label { get; set; }
   }

I need to create a JSONP file. I hope to get something like this

Places({"id": 1, "label": "London"}, {"id": 2, "label": "Paris"})

I tried use

JsonSerializer serializer = new JsonSerializer();  ´
JavaScriptSerializer s = new JavaScriptSerializer();
using (StreamWriter file = File.CreateText("myJson.json"))
{
    serializer.Serialize(file, string.Format("{0}({1})", "Places", s.Serialize(places)));
    file.Close();
}

But my result file is this:

"Places([{\"id\":1,\"label\":\"London\"}, {\"id\":2,\"label\":\"Paris\"}])"

And this result does not working for my for the ' \" ' chars

Josema Pereira
  • 101
  • 1
  • 8

1 Answers1

1

You are serializing your original data as JSON twice so result is JSON containing string which itself is JSON.

You should simply do string concatenation of JSON with suffix/prefix as shown for example in How can I manage ' in a JSONP response?:

var jsonpPrefix = "Places"  + "(";
var jsonpSuffix = ")";
var jsonp = 
    jsonpPrefix + 
    s.Serialize(places) + 
    jsonpSuffix);

The easiest way to write it to file is just File.WriteAllText("myJson.jsonp", jsonp).

Alternatively instead of constructing string first just write it directly to file

using (StreamWriter sw = new StreamWriter("myJson.jsonp"))  
{
    sw.Write("Places(");
    sw.Write(s.Serialize(places));
    sw.Write(")"
}  

Side note: saving JSONP to file is somewhat strange as it usually just send as response to cross-domain AJAX request - so make sure you really need JSONP and not just JSON.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179