简体   繁体   English

WCF JSON Web服务删除方括号

[英]WCF JSON web service remove square brackets

There seems to be a few questions around this, but I can't seem to find a conclusive answer. 围绕此问题似乎有一些问题,但我似乎找不到最终的答案。

I've created a WCF JSON web service that returns perfect JSON and this has been clarified using jsonlint.com. 我创建了一个WCF JSON Web服务,该服务返回了完美的JSON,并且已经使用jsonlint.com进行了澄清。 The web service returns an array (List< myresults>) and this seems to format the JSON with square brackets, like so: Web服务返回一个数组(List <myresults>),这似乎用方括号将JSON格式化,如下所示:

[{"Image":"http://www.mywebsite/myimage.jpg"}] [{“ Image”:“ http://www.mywebsite/myimage.jpg”}]

Parsing the JSON on the iPhone platform seems to handle the backslashes fine, but it does not play nice with the square brackets - I had to manually remove these using this: 在iPhone平台上解析JSON似乎可以很好地处理反斜杠,但在方括号中不能很好地发挥作用-我必须使用以下方法手动将其删除:

[str stringByReplacingOccurrencesOfString:@"[" withString:@""]; [str stringByReplacingOccurrencesOfString:@“ [” withString:@“”]]; //(for each bracket) //(每个括号)

However, I would also like to consume the same JSON in an HTML webpage using jquery and it seems I am faced with the same issue. 但是,我也想使用jquery在HTML网页中使用相同的JSON,看来我也面临同样的问题。 Surely there is a more appropriate way to deal with these annoying square brackets? 当然,有更适当的方法来处理这些令人讨厌的方括号吗?

I'd really appreciate if someone could post an easy way to handle the brackets - either removing them from the web service, or in my javascript code. 如果有人可以发布一种简单的方法来处理方括号,我将不胜感激-将其从Web服务中删除或在我的JavaScript代码中删除。

Thanks! 谢谢!

If it helps, my Javascript is as follows: 如果有帮助,我的Javascript如下:

$.getJSON(urlToMyWebService, function(data) { $ .getJSON(urlToMyWebService,function(data){

  var items = []; $.each(data, function(key, val) { items.push('<li id="' + key + '">' + val + '</li>'); }); $('<ul/>', { 'class': 'my-new-list', html: items.join('') }).appendTo('body'); }); 

The square brackets just indicate an array. 方括号仅表示一个数组。 As you noted, since you're returning an array, it'll have the square brackets. 如您所述,由于要返回数组,因此将带有方括号。

You'll need to have an array on the JavaScript/Objective C side as well, that's all. 您还需要在JavaScript / Objective C端有一个数组,仅此而已。

First things first ids in HTML cannot start with numbers, so using key as id for your li is invalid. 首先,HTML中的第一个id不能以数字开头,因此将key用作li id无效。 Second your JSON list contains objects with Image property so you probably want this: 其次,您的JSON列表包含具有Image属性的对象,因此您可能需要这样做:

$.each(data, function(key, val) {
    items.push('<li id="li_' + key + '">' + val.Image + '</li>');
});

and here's a live demo . 这是一个现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM