当前位置: 代码迷 >> JavaScript >> json解析跟处理
  详细解决方案

json解析跟处理

热度:147   发布时间:2012-06-26 10:04:13.0
json解析和处理
  在android调用webservice时,经常要对json的格式进行处理,现在有两种方法

  去处理:

  1 使用JSONObject 和 JSONTokener去解析

  2 使用GSON库

  先看第一种方法,假如有如下的json字符串:

java代码:

{
  “name”: “myName”,
  “message”: ["myMessage1","myMessage2"],
  “place”: “myPlace”,
  “date”: ”thisDate”
  }

       第一种解决方法:

java代码:

public class main extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  try {
  TextView tv = (TextView)findViewById(R.id.TextView01);
  String json = “{”
  + “ ”name”: ”myName”, ”
  + “ ”message”: [\"myMessage1\",\"myMessage2\"],”
  + “ ”place”: ”myPlace”, ”
  + “ ”date”: ”thisDate” ”
  + “}”;
  /* Create a JSON object and parse the required values */
  JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
  String name = object.getString(“name”);
  String place = object.getString(“place”);
  String date = object.getString(“date”);
  JSONArray message = object.getJSONArray(“message”);
  tv.setText(“Name: “+ name +” ”);
  tv.append(“Place: “+ place +” ”);
  tv.append(“Date: “+ date +” ”);
  for(int i=0;i< p>
  {
  tv.append(“Message: “+ message.getString(i) +” ”);
  }

       2 使用GSON类库
  GOOGLE提供的gson类库,地址在:

java代码:

public class JSON_structure {
  public String name;
  public String place;
  public String date;
  public String[] message;
  }

       这其实是个POJO类

java代码:

try {
  /* Inflate TextView from the layout */
TextView tv = (TextView)findViewById(R.id.TextView01);
  /* JSON data considered as an example. Generally this data is obtained
  from a web service.*/
  String json = “{”
  + “ ”name”: ”myName”, ”
  + “ ”message”: [\"myMessage1\",\"myMessage2\"],”
  + “ ”place”: ”myPlace”, ”
  + “ ”date”: ”thisDate” ”
  + “}”;
  Gson gson = new Gson();
  JSON_structure obj= gson.fromJson(json, JSON_structure.class);
  tv.setText(“Name: “+ obj.name +” ”);
  tv.append(“Place: “+ obj.place +” ”);
  tv.append(“Date: “+ obj.date +” ”);
  for(int i=0;i< p>
  {
  tv.append(“Message: “+ obj.message +” ”);
  }
  }
  catch(Exception ex){ex.printStackTrace();}
  }
  } catch (JSONException e) {e.printStackTrace();}
  catch(Exception ex){ex.printStackTrace();}
  }
  }
  相关解决方案