LSX-blog

Feed Rss

【收录】JSON 数据格式解析

12.23.2011, 网络, by .

和 XML 一样,JSON 也是基于纯文本的数据格式。由于 JSON 天生是为 JavaScript 准备的,因此,JSON 的数据格式非常简单,您可以用 JSON 传输一个简单的 String,Number,Boolean,也可以传输一个数组,或者一个复杂的 Object 对象。

String,Number 和 Boolean 用 JSON 表示非常简单。例如,用 JSON 表示一个简单的 String “ abc ”,其格式为:

“abc”
除了字符 “,/,/ 和一些控制符(/b,/f,/n,/r,/t)需要编码外,其他 Unicode 字符可以直接输出。下图是一个 String 的完整表示结构:

图 1. String 的完整表示结构

一个 Number 可以根据整型或浮点数表示如下:

这与绝大多数编程语言的表示方法一致,例如:

12345(整数) -3.9e10(浮点数)
Boolean 类型表示为 true 或 false 。此外,JavaScript 中的 null 被表示为 null,注意,true、false 和 null 都没有双引号,否则将被视为一个 String 。

JSON 还可以表示一个数组对象,使用 [] 包含所有元素,每个元素用逗号分隔,元素可以是任意的 Value,例如,以下数组包含了一个 String,Number,Boolean 和一个 null:

[“abc”,12345,false,null]
Object 对象在 JSON 中是用 {} 包含一系列无序的 Key-Value 键值对表示的,实际上此处的 Object 相当于 Java 中的 Map<String, Object>,而不是 Java 的 Class 。注意 Key 只能用 String 表示。

例如,一个 Address 对象包含如下 Key-Value:

city:Beijing street:Chaoyang Road postcode:100025(整数)
用 JSON 表示如下:

{“city”:”Beijing”,”street”:” Chaoyang Road “,”postcode”:100025}
其中 Value 也可以是另一个 Object 或者数组,因此,复杂的 Object 可以嵌套表示,例如,一个 Person 对象包含 name 和 address 对象,可以表示如下:

{“name”:”Michael”,”address”: {“city”:”Beijing”,”street”:” Chaoyang Road “,”postcode”:100025} }
JavaScript 处理 JSON 数据

上面介绍了如何用 JSON 表示数据,接下来,我们还要解决如何在服务器端生成 JSON 格式的数据以便发送到客户端,以及客户端如何使用 JavaScript 处理 JSON 格式的数据。

我们先讨论如何在 Web 页面中用 JavaScript 处理 JSON 数据。我们通过一个简单的 JavaScript 方法就能看到客户端如何将 JSON 数据表示给用户:

function handleJson() { var j={“name”:”Michael”,”address”: {“city”:”Beijing”,”street”:” Chaoyang Road “,”postcode”:100025} }; document.write(j.name); document.write(j.address.city); }
假定服务器返回的 JSON 数据是上文的:

{“name”:”Michael”,”address”: {“city”:”Beijing”,”street”:” Chaoyang Road “,”postcode”:100025} }
只需将其赋值给一个 JavaScript 变量,就可以立刻使用该变量并更新页面中的信息了,相比 XML 需要从 DOM 中读取各种节点而言,JSON 的使用非常容易。我们需要做的仅仅是发送一个 Ajax 请求,然后将服务器返回的 JSON 数据赋值给一个变量即可。有许多 Ajax 框架早已包含了处理 JSON 数据的能力,例如 Prototype(一个流行的 JavaScript 库:http://prototypejs.org)提供了 evalJSON() 方法,能直接将服务器返回的 JSON 文本变成一个 JavaScript 变量:

new Ajax.Request(“http://url”, { method: “get”, onSuccess: function(transport) { var json = transport.responseText.evalJSON(); // TODO: document.write(json.xxx); } });
服务器端输出 JSON 格式数据

下面我们讨论如何在服务器端输出 JSON 格式的数据。以 Java 为例,我们将演示将一个 Java 对象编码为 JSON 格式的文本。

将 String 对象编码为 JSON 格式时,只需处理好特殊字符即可。另外,必须用 (“) 而非 (‘) 表示字符串:

static String string2Json(String s) { StringBuilder sb = new StringBuilder(s.length()+20); sb.append(‘/”‘); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); switch (c) { case ‘/”‘: sb.append(“///””); break; case ‘//’: sb.append(“////”); break; case ‘/’: sb.append(“///”); break; case ‘/b’: sb.append(“//b”); break; case ‘/f’: sb.append(“//f”); break; case ‘/n’: sb.append(“//n”); break; case ‘/r’: sb.append(“//r”); break; case ‘/t’: sb.append(“//t”); break; default: sb.append(c); } } sb.append(‘/”‘); return sb.toString(); }
将 Number 表示为 JSON 就容易得多,利用 Java 的多态,我们可以处理 Integer,Long,Float 等多种 Number 格式:

static String number2Json(Number number) { return number.toString(); }
Boolean 类型也可以直接通过 toString() 方法得到 JSON 的表示:

static String boolean2Json(Boolean bool) { return bool.toString(); }
要将数组编码为 JSON 格式,可以通过循环将每一个元素编码出来:

static String array2Json(Object[] array) { if (array.length==0) return “[]”; StringBuilder sb = new StringBuilder(array.length << 4); sb.append(‘[‘); for (Object o : array) { sb.append(toJson(o)); sb.append(‘,’); } // 将最后添加的 ‘,’ 变为 ‘]’: sb.setCharAt(sb.length()-1, ‘]’); return sb.toString(); }
最后,我们需要将 Map<String, Object> 编码为 JSON 格式,因为 JavaScript 的 Object 实际上对应的是 Java 的 Map<String, Object> 。该方法如下:

static String map2Json(Map<String, Object> map) { if (map.isEmpty()) return “{}”; StringBuilder sb = new StringBuilder(map.size() << 4); sb.append(‘{‘); Set<String> keys = map.keySet(); for (String key : keys) { Object value = map.get(key); sb.append(‘/”‘); sb.append(key); sb.append(‘/”‘); sb.append(‘:’); sb.append(toJson(value)); sb.append(‘,’); } // 将最后的 ‘,’ 变为 ‘}’: sb.setCharAt(sb.length()-1, ‘}’); return sb.toString(); }
为了统一处理任意的 Java 对象,我们编写一个入口方法 toJson(Object),能够将任意的 Java 对象编码为 JSON 格式:

public static String toJson(Object o) { if (o==null) return “null”; if (o instanceof String) return string2Json((String)o); if (o instanceof Boolean) return boolean2Json((Boolean)o); if (o instanceof Number) return number2Json((Number)o); if (o instanceof Map) return map2Json((Map<String, Object>)o); if (o instanceof Object[]) return array2Json((Object[])o); throw new RuntimeException(“Unsupported type: ” + o.getClass().getName()); }
我们并未对 Java 对象作严格的检查。不被支持的对象(例如 List)将直接抛出 RuntimeException 。此外,为了保证输出的 JSON 是有效的,Map<String, Object> 对象的 Key 也不能包含特殊字符。细心的读者可能还会发现循环引用的对象会引发无限递归,例如,精心构造一个循环引用的 Map,就可以检测到 StackOverflowException:

@Test(expected=StackOverflowError.class) public void testRecurrsiveMap2Json() { Map<String, Object> map = new HashMap<String, Object>(); map.put(“key”, map); JsonUtil.map2Json(map); }
好在服务器处理的 JSON 数据最终都应该转化为简单的 JavaScript 对象,因此,递归引用的可能性很小。

最后,通过 Servlet 或 MVC 框架输出 JSON 时,需要设置正确的 MIME 类型(application/json)和字符编码。假定服务器使用 UTF-8 编码,则可以使用以下代码输出编码后的 JSON 文本:

response.setContentType(“application/json;charset=UTF-8”); response.setCharacterEncoding(“UTF-8”); PrintWriter pw = response.getWriter(); pw.write(JsonUtil.toJson(obj)); pw.flush();
小结

JSON 已经是 JavaScript 标准的一部分。目前,主流的浏览器对 JSON 支持都非常完善。应用 JSON,我们可以从 XML 的解析中摆脱出来,对那些应用 Ajax 的 Web 2.0 网站来说,JSON 确实是目前最灵活的轻量级方案。

【收录】JSON 数据格式解析 有 45 条回应

  1. This site truly has all the info I needed concerning this subject and
    didn’t know who to ask.

    回复
  2. If you want to get much from this article then you have
    to apply such methods to your won weblog.

    回复
  3. [url=https://finasteridealop.com/]propecia 5mg[/url]

    回复
  4. This website definitely has all of the info I needed about this subject and didn’t
    know who to ask.

    回复
  5. [url=http://robaxinmed.com/]buy robaxin[/url]

    回复
  6. Painter And Decorator Gloucester
    38 Bruton Way
    Gloucester GL1 1DA, United Kingdom
    01452 223268

    回复
  7. Greetings! Very useful advice in this particular article!
    It’s the little changes that make the greatest changes.
    Thanks for sharing!

    回复
  8. Hello to all, for the reason that I am actually keen of reading this webpage’s post to be updated on a regular basis. It contains pleasant material.|

    回复
  9. [url=http://advair1.com/]purchase advair online[/url] [url=http://aqutaneiso.com/]buy accutane[/url] [url=http://diflucanmed.com/]buy diflucan without a prescription[/url] [url=http://ventolinalb.com/]ventolin hfa[/url] [url=http://celebrexcap.com/]celebrex generic[/url] [url=http://doxycycline360.com/]doxycycline tablet 100 mg[/url] [url=http://cipro360.com/]cipro over the counter mexico[/url] [url=http://atorvastatinlipitor.com/]lipitor generic[/url]

    回复
  10. Thank you, I’ve recently been searching for info about this subject for a while and
    yours is the best I’ve found out so far. However, what about the conclusion? Are you sure
    in regards to the supply?

    回复
  11. Pretty! This has been an incredibly wonderful post. Thank
    you for providing this info.

    回复
  12. I was curious if you ever considered changing the structure of your blog?
    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so
    people could connect with it better. Youve got an awful lot of text for only
    having 1 or two pictures. Maybe you could space it out better?

    回复
  13. Very soon this web page will be famous amid all blog viewers, due to it’s fastidious content

    回复
  14. Hola! I’ve been following your site for some time
    now and finally got the bravery to go ahead and give
    you a shout out from Kingwood Texas! Just wanted to mention keep up
    the great work!

    回复
  15. Hello, i think that i saw you visited my website so i came to “return the favor”.I’m attempting to find things to improve
    my website!I suppose its ok to use some of your ideas!!

    回复
  16. If some one needs expert view concerning blogging then i advise him/her
    to pay a visit this blog, Keep up the good work.

    回复
  17. Howdy very nice blog!! Man .. Beautiful .. Wonderful .. I’ll bookmark your blog and take the feeds additionally?
    I’m glad to find so many useful information right here within the publish, we’d like develop extra techniques in this regard, thanks for sharing.
    . . . . .

    回复
  18. This is a topic that’s near to my heart… Thank you!
    Where are your contact details though?

    回复
  19. I blog quite often and I really appreciate your information. This great article has
    truly peaked my interest. I will bookmark your
    blog and keep checking for new information about once a
    week. I opted in for your RSS feed too.

    回复
  20. What’s up, every time i used to check webpage posts here early in the daylight, since i like to
    gain knowledge of more and more.

    回复
  21. Hi everyone, it’s my first visit at this web page, and paragraph is in fact
    fruitful in favor of me, keep up posting such articles or
    reviews.

    回复
  22. It’s amazing in support of me to have a web page, which is valuable designed for my know-how.
    thanks admin

    回复
  23. Keep this going please, great job!

    回复
  24. I’m gone to convey my little brother, that he should also pay a
    quick visit this webpage on regular basis to take updated from most recent news.

    回复
  25. I was able to find good advice from your blog posts.

    回复
  26. If you would like to improve your know-how just keep visiting
    this web page and be updated with the hottest gossip posted
    here.

    回复
  27. Appreciate this post. Let me try it out.

    回复
  28. whoah this blog is fantastic i like reading your articles.

    Keep up the great work! You already know, lots of persons
    are hunting round for this information, you could help them greatly.

    回复
  29. Fastidious answers in return of this issue with firm arguments and telling the
    whole thing regarding that.

    回复
  30. Spot on with this write-up, I absolutely think this site
    needs a great deal more attention. I’ll probably
    be returning to read more, thanks for the information!

    回复
  31. I enjoy, lead to I discovered just what I used to be taking
    a look for. You have ended my four day long hunt! God Bless you man. Have a
    nice day. Bye

    回复
  32. whoah this weblog is great i love reading your posts. Keep up the good work!
    You already know, a lot of persons are looking
    round for this info, you can help them greatly.

    回复
  33. Whats up are using WordPress for your site platform?
    I’m new to the blog world but I’m trying to get started and set up my own. Do you require any html coding
    knowledge to make your own blog? Any help would be really appreciated!

    回复
  34. What’s up, its pleasant piece of writing regarding media print, we all be
    familiar with media is a great source of information.

    回复
  35. I’m curious to find out what blog platform you have been working with?
    I’m having some small security problems with my latest
    website and I’d like to find something more secure. Do
    you have any solutions?

    回复
  36. This is my first time go to see at here and i am actually impressed to read all at
    alone place.

    回复
  37. Simply wish to say your article is as astounding. The clarity to your submit is simply spectacular and that i can suppose you
    are a professional on this subject. Fine along with your
    permission allow me to seize your feed to keep updated with coming near near post.

    Thank you one million and please carry on the enjoyable work.

    回复
  38. Hi there colleagues, how is everything, and what you want to say about this paragraph, in my view its actually remarkable in support of me.

    回复
  39. hi!,I like your writing very a lot! share we keep up a correspondence extra approximately your post on AOL?
    I need an expert on this house to solve my
    problem. Maybe that is you! Looking forward to see you.

    回复
  40. Hi just wanted to give you a quick heads up and let you know a few
    of the pictures aren’t loading properly. I’m not
    sure why but I think its a linking issue.
    I’ve tried it in two different browsers and both show the same results.

    回复
  41. I absolutely love your blog and find many of your post’s to be just what I’m
    looking for. can you offer guest writers to write content to suit your needs?
    I wouldn’t mind creating a post or elaborating on many of the subjects you write regarding here.
    Again, awesome blog!

    回复
  42. Great blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple adjustements would really
    make my blog stand out. Please let me know where you got your theme.

    Cheers

    回复
  43. Great blog you have here.. It’s hard to find excellent writing like yours nowadays.
    I seriously appreciate individuals like you!
    Take care!!

    回复
  44. This post is priceless. Where can I find out more?

    回复
  45. is muy barata

    fe25 bestall is pa natet

    回复

发表评论

电子邮件地址不会被公开。 必填项已用*标注