43668

Getting invalid string [ ] around my JSON outputted from using the JavascriptSerializer class

Question:

Currently I'm using the helper methods outlined here to return some JSON from my .ashx: <a href="http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx" rel="nofollow">http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx</a>

Problem is, I get [ and ] wrapped around my JSON which is malformed...jQuery cannot pick it up in the callback:

[{"ImageTag":"&lt;img src=&quot;http://www.xxx.com/image/473.jpg&quot; alt=&quot;&quot;&gt;"},{"ImageTag":"&lt;img src=&quot;http://www.xxx.com/image/485.jpg&quot; alt=&quot;&quot;&gt;"}]

So I don't know why I get brackets around this. Here is my implementation:

private void GetImagesJSON(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = Encoding.UTF8.ToString(); int i = 1; List<Product> products = GetTestProducts(); List<CtImageList> imageList = new List<CtImageList>(); foreach(Product p in products) { string imageTag = HttpUtility.HtmlEncode(string.Format(@"<img src=""{0}"" alt="""">", ImageUrl(p.Image, false))); imageList.Add(new CtImageList{ImageTag = imageTag}); i++; } string jsonString = imageList.ToJSON(); context.Response.Write(jsonString); }

Here is the callback function in jQuery which can't parse that because of the starting [ and ]:

function itemLoadCallback(carousel, state) { // Only load items if they don't already exist if (carousel.has(carousel.first, carousel.last)) { return; } $.getJSON("http://localhost:59396/xxx/CHandler.ashx?action=productsjson", function(data) { $.each(data.items, function(i, item) { alert('got here'); carousel.add(i, mycarousel_decodeEntities(item.ImageTag)); if (i == 3) return false; }); }); };

Answer1:

AFAIK, your response is well-formatted JSON. The brackets are there to tell javascript parses that you are using an array. Passing your JSON to eval() would return you an array with 2 objects.

If your callback is waiting for a single "ImageTag" object, you will get an error.

Answer2:

Actually, that should be valid json. The "[" and "]" indicate a list because you called ToJSON on a list of objects. So you have to treat the results as an array. Check out the sample below...

<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ var a = eval("[1,2,3]"); for(var i in a) { $("#results").append("

" + a[i] + "

"); } }); </script> <div id="results"></div>

so for your code the function is:

var images = eval('[{"ImageTag":"&lt;img src=&quot;http://www.xxx.com/image/473.jpg&quot; alt=&quot;&quot;&gt;"},{"ImageTag":"&lt;img src=&quot;http://www.xxx.com/image/485.jpg&quot; alt=&quot;&quot;&gt;"}]'); for(var i in images){ $("#mydiv").append(images[i].ImageTag); }

Recommend

  • Converting a String to an Int Array [duplicate]
  • jquery retrieve relatedTarget.data('url') value
  • Round bracket in string with JDBC prepared statement
  • Formatting Pascal's triangle
  • How to test if a process is running with grep in bash?
  • How to read .rtf File from URL in iPhone App
  • Weird multiplicator operator behavior in a two arrays to hash combination
  • Length of Greek character string is larger than it should be
  • How to keep spaces within angle brackets of C++ casting operators in Visual C++ 2015?
  • X509 store can not find certificate by SerialNumber
  • Is the scope of a variable initialized in a for loop declaration actually more than just block scope
  • How to filter local requests in asp.net web api?
  • Reference generic url parameter in AuthorizeAttribute
  • Pandas column creation
  • Matching multiple strings to one long string using patterns
  • How do I split this string into an array?
  • Use sed with regex and (
  • What's the syntax to inherit documentation from another indexer?
  • What Makes These Two Array Adds Different?
  • abstracting over a collection
  • Can't remove headers after they are sent
  • Why use database factory in asp.net mvc?
  • C++ pointer value changes with static_cast
  • How do I configure context broker accept post requests from my remote sensor?
  • WPF ICommand CanExecute(): RaiseCanExecuteChanged() or automatic handling via DispatchTimer?
  • Regex thinks I'm nesting, but I'm not
  • Opengl-es onTouchEvents problem or a draw problem? [closed]
  • output of program is not same as passed argument
  • Javascript Callbacks with Object constructor
  • Javascript + PHP Encryption with pidCrypt
  • File upload with ng-file-upload throwing error
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • AngularJs get employee from factory
  • Getting Messege Twice Using IMvxMessenger
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • How can i traverse a binary tree from right to left in java?
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?