JSON对象操作
程序员文章站
2022-03-05 23:29:25
...
数据样本:
[{
results:
{
itemCount:100,
startIndex:10,
currentCount:2,
item:
[
{
buyerId:234,
buyerTime:'1245785214',
price:3.0,
buyerNickName:'sdf',
buyerIconUrl:’http://safasdfasdf’
},
{
buyerId:234,
buyerTime:'1245785214',
price:3.0,
buyerNickName:'sdf',
buyerIconUrl:’http://safasdfasdf’
}
]
}
}]
JSON实现:
应用JSONObject存储Map类型数值:
[{
results:
{
itemCount:100,
startIndex:10,
currentCount:2,
item:
[
{
buyerId:234,
buyerTime:'1245785214',
price:3.0,
buyerNickName:'sdf',
buyerIconUrl:’http://safasdfasdf’
},
{
buyerId:234,
buyerTime:'1245785214',
price:3.0,
buyerNickName:'sdf',
buyerIconUrl:’http://safasdfasdf’
}
]
}
}]
JSON实现:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.json);
TextView tv01 = (TextView)findViewById(R.id.tv01);
TextView tv02 = (TextView)findViewById(R.id.tv02);
try {
JSONObject jo1 = new JSONObject();
jo1.put("buyerId", 123);
jo1.put("buyerTime", "'1245785214'");
jo1.put("price", 3.0);
jo1.put("buyerNickName", "'aaaa'");
JSONObject jo2 = new JSONObject();
jo2.put("buyerId", 234);
jo2.put("buyerTime", "'1111332222'");
jo2.put("price", 4.0);
jo2.put("buyerNickName", "'bbbb'");
JSONArray jarr1 = new JSONArray();
jarr1.put(jo1);
jarr1.put(jo2);
JSONObject jo3 = new JSONObject();
jo3.put("itemCount", 100);
jo3.put("startIndex", 10);
jo3.put("currentCount", 2);
jo3.put("item", jarr1);
JSONObject jo4 = new JSONObject();
jo4.put("results", jo3);
JSONArray jarr2 = new JSONArray();
jarr2.put(jo4);
tv01.setText(jarr2.toString());
JSONObject json = jarr2.getJSONObject(0);
tv02.setText(json.getString("results"));
} catch (JSONException e) {
e.printStackTrace();
}
}
应用JSONObject存储Map类型数值:
public static JSONObject getJSON(Map map) {
Iterator iter = map.entrySet().iterator();
JSONObject holder = new JSONObject();
while (iter.hasNext()) {
Map.Entry pairs = (Map.Entry) iter.next();
String key = (String) pairs.getKey();
Map m = (Map) pairs.getValue();
JSONObject data = new JSONObject();
try {
Iterator iter2 = m.entrySet().iterator();
while (iter2.hasNext()) {
Map.Entry pairs2 = (Map.Entry) iter2.next();
data.put((String) pairs2.getKey(), (String) pairs2.getValue());
}
holder.put(key, data);
} catch (JSONException e) {
Log.e("Transforming", "There was an error packaging JSON",e);
}
}
return holder;
}
推荐阅读
-
android操作SQLite增删改减实现代码
-
C#跨窗体操作(引用传递) 实例代码
-
Zend Framework教程之Zend_Registry对象用法分析
-
C#利用com操作excel释放进程的解决方法
-
android+json+php+mysql实现用户反馈功能方法解析
-
Json.net 常用使用小结(推荐)
-
asp.net提取多层嵌套json数据的方法
-
asp.net DataTable相关操作集锦(筛选,取前N条数据,去重复行,获取指定列数据等)
-
mysql 存储过程中变量的定义与赋值操作
-
asp.net DataTable相关操作集锦(筛选,取前N条数据,去重复行,获取指定列数据等)