
如果不是Android开发环境的话,首先需要引入处理JSON数据的包:json-lib-2.2.3-jdk15.jar
Java样例程序如下:
import net.sf.json.JSONArrayimport net.sf.json.JSONObject
public class DoJSON {
public static void main(String[] args) {
JSONArray employees = new JSONArray() //JSON数组
JSONObject employee = new JSONObject() //JSON对象
employee.put("firstName", "Bill") //按“键-值”对形式存储数据到JSON对象中
employee.put("lastName", "Gates")
employees.add(employee) //将JSON对象加入到JSON数组中
employee.put("firstName", "George")
employee.put("lastName", "Bush")
employees.add(employee)
employee.put("firstName", "Thomas")
employee.put("lastName", "Carter")
employees.add(employee)
System.out.println(employees.toString())
for(int i=0 i<employees.size() i++) {
JSONObject emp = employees.getJSONObject(i)
System.out.println(emp.toString())
System.out.println("FirstName :\t" + emp.get("firstName"))
System.out.println("LastName : \t" + emp.get("lastName"))
}
}
}
运行效果:
[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]
{"firstName":"Bill","lastName":"Gates"}
FirstName : Bill
LastName : Gates
{"firstName":"George","lastName":"Bush"}
FirstName : George
LastName : Bush
{"firstName":"Thomas","lastName":"Carter"}
FirstName : Thomas
LastName : Carter
import org.json.JSONArrayimport org.json.JSONException
public class test2 {
public static void main(String[] args) throws JSONException {
String str = "[{'columnId':5,'columnName':'人文历史'},{'columnId':2,'columnName':'商业视野'}]}"
JSONArray jsonArray = null
jsonArray = new JSONArray(str)
System.out.println(jsonArray.getJSONObject(0).get("columnName"))
}
}
需要引入json.jar
获取JSON的值。 就是解析JSON数据.
如果是简单的JSON数据, 并且只需要提取少量数据的值, 那么可以使用字符串的 *** 作来实现,比如String.subString()...等
如果是比较复杂的JSON数据,或者需要提取的值比较多, 那么可以使用Gson, FastJSon 等第三方的jar来实现...
简单的Demo示例
第三方包使用的是Gson
import com.google.gson.JsonElementimport com.google.gson.JsonObject
import com.google.gson.JsonParser
public class GsonTest {
public static void main(String[] args) {
String strJson = "{ \"name\": \"张三\", \"age\": 12 }"
JsonParser parser = new JsonParser()
JsonElement je = parser.parse(strJson)
JsonObject jobj = je.getAsJsonObject()//从json元素转变成json对象
String name = jobj.get("name").getAsString()//从json对象获取指定属性的值
System.out.println(name)
int age = jobj.get("age").getAsInt()
System.out.println(age)
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)