欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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实现:
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;
}
相关标签: json