项目实战,小结项目开发中的得与失,在项目中做了JSON的数据封装与解析,为以后网络传输做铺垫,用到了以下几个知识点,在这里和大家分享一下: 

先简单说一下背景知识:


JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 它基于JavaScript Programming LanguageStandard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。

JSON建构于两种结构:

  • “名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
  • 值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。

这些都是常见的数据结构。事实上大部分现代计算机语言都以某种形式支持它们。这使得一种数据格式在同样基于这些结构的编程语言之间交换成为可能。

JSON具有以下这些形式:

对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。

数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间使用“,”(逗号)分隔。

值(value)可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array)。这些结构可以嵌套。

字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。

字符串(string)与C或者Java的字符串非常相似。

数值(number)也与C或者Java的数值非常相似。除去未曾使用的八进制与十六进制格式。除去一些编码细节。

空白可以加入到任何符号之间。 以下描述了完整的语言。

JSON官网:http://www.json.org/json-zh.html




JSONObject

extends 

Object



java.lang.Object

   ↳

org.json.JSONObject

Class Overview


A modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObjectsJSONArrays, Strings, Booleans, Integers, Longs, Doubles or NULL. Values may not be nullNaNsinfinities, or of any type not listed here.

This class can coerce values to another type when requested.

  • When the requested type is a boolean, strings will be coerced using a case-insensitive comparison to "true" and "false".
  • When the requested type is a double, other 

Number

  •  types will be coerced using 

doubleValue

  • . Strings that can be coerced using 

valueOf(String)

  • When the requested type is an int, other 

Number

  •  types will be coerced using 

intValue

  • . Strings that can be coerced using 

valueOf(String)

  • When the requested type is a long, other 

Number

  •  types will be coerced using 

longValue

  • . Strings that can be coerced using 

valueOf(String)

  • When the requested type is a String, other non-null values will be coerced using 

valueOf(Object)

  • . Although null cannot be coerced, the sentinel value 

NULL

This class can look up both mandatory and optional values:

  • Use 

getType()

  •  to retrieve a mandatory value. This fails with a 

JSONException

  • Use 

optType()Warning: this class represents null in two incompatible ways: the standard Java null reference, and the sentinel value NULL. In particular, calling put(name, null) removes the named entry from the object but put(name, JSONObject.NULL) stores an entry whose value is JSONObject.NULL.

Instances of this class are not thread safe. Although this class is nonfinal, it was not designed for inheritance and should not be subclassed. In particular, self-use by overrideable methods is not specified. See Effective Java Item 17, "Design and Document or inheritance or else prohibit it" for further information.


Android API:http://www.android-doc.com/reference/org/json/JSONObject.html


源代码,主要就是JSONObject类以及它的getX和put方法:


JSONObject jsonObjectServer = new JSONObject();
                try {
                    jsonObjectServer.put("content",contentCur);
                    jsonObjectServer.put("owner",ownerCur);
                    jsonObjectServer.put("time",timeCur);
                    Log.d(TAG + "模拟服务器JSON:", jsonObjectServer.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                    JSONObject jsonObjectClient = new JSONObject(jsonObjectServer.toString());
                    Log.d(TAG + "解析后->", "content:" + jsonObjectClient.getString("content")
                            + ", owner:" + jsonObjectClient.getString("owner")
                            + ", time:" + jsonObjectClient.getString("time") );
                } catch (JSONException e) {
                    e.printStackTrace();
                }





常见问题:

你可能遇到了如下问题:


Exception in thread "main"java.lang.RuntimeException: Stub!

一般来说出现这个异常的原因是:一个地方调用了不属于这个地方的库。比如我写java程序,但是我导入了android的相关包,调用android相关包时候会出发这个异常。

在Java工程中尝试使用Android库中的org.json.JSONObject类,在执行时出现“Stub!”错误,

执行代码

// Load the requested page converted to a string into a JSONObject.
          JSONObject jsonResponse = newJSONObject(sb.toString());

控制台显示错误:

        Exception in thread "main" java.lang.RuntimeException: Stub!
               atorg.json.JSONObject.<init>(JSONObject.java:8)

Android工程和Java工程还有一定的差异,不能混用他们的库,和函数入口方法。将上面的代码,移植到在Android工程可以正确执行!

再说另一个异常:java.lang.NoClassDefFoundError. 这个是我写android引用了一个javaproject里的类。显示类找不到定义异常。没有办法,直接把这个java project里的类复制到android 的工程里。




文末小彩蛋:

AS快捷键:ctrl+alt+h,查看方法在哪被调用

AS中Jar包的导入与删除:


添加jar包:

将jar包添加到 libs目录,libs文件夹在  app文件夹下(没有libs目录就自己手动创建个,app/libs )

然后在libs文件夹和添加的*.jar文件下鼠标单击菜单add as library

然后在选择项目单击Open Module Settings,在Dependencies中选择添加文件

这样就完成了jar文件添加。

当然,也可以直接手动完成添加,如下所述:

打开App目录下有个build.gradle文件应该项目结构文件,上述的动作只是为了在在文件下添加

dependencies {
compile files ('/libs/xxx.jar');
    compile fileTree(dir: 'libs',include: ['*.jar'])
    compile'com.android.support:support-v4:22.1.1'
    compilefiles('libs/joda-time-2.8.jar')
}

然后clean项目。


删除jar包(直接选中项目,按F4):

点击 File——>Project structure——>module——>app

选择 “dependencies”。选择你要删除的jar包