JSONオブジェクト操作
データサンプル:
[{
レスリング:
{
itemenCount:100、
startIndex:10、
currentCount:2、
アイテム:
[
{
buyerId:234、
buyerTime:'1245785214'
price:3.0、
buyer NickName:'sdf'
buyerIconUrl:'http://safasdfasdf”
}
{
buyerId:234、
buyerTime:'1245785214'
price:3.0、
buyer NickName:'sdf'
buyerIconUrl:'http://safasdfasdf”
)
」
)
}
JSON実現:
[{
レスリング:
{
itemenCount:100、
startIndex:10、
currentCount:2、
アイテム:
[
{
buyerId:234、
buyerTime:'1245785214'
price:3.0、
buyer NickName:'sdf'
buyerIconUrl:'http://safasdfasdf”
}
{
buyerId:234、
buyerTime:'1245785214'
price:3.0、
buyer NickName:'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;
}