如何在android中解析JSON格式的String

时间:2014-10-24 18:51:12

标签: android json

我从GSON格式的GCM收到一个字符串。我想解析那个字符串,然后生成notification.i希望它应该基于标签生成通知,例如标签是"评论"那么它应该生成评论通知。我是Android新手。  我收到的字符串是     {"标记":"评价""发件人":空,"内容":空} 我的代码是

public void categorizNotifications(String msg){
    try {
        JSONObject json=new JSONObject(msg);
        String Tag=json.getString(TAG);
        if(Tag=="comment"){
            String Content=json.getString(CONTENT);

            String Sender=json.getString(SENDER);
            generateNotificationForComment(Content,Sender);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private void generateNotificationForComment(String content2, String sender2) {
    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, Comments.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.ic_action_event)
            .setContentTitle(sender2+" add a comment")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(content2))
            .setContentText(content2);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    //Log.d(TAG, "Notification sent successfully.");

}

1 个答案:

答案 0 :(得分:1)

有几种方法可以解析json对象。我个人建议google gson library

  1. 您必须下载库jar并将其添加到您的项目中。
  2. 然后你必须编写一个你要解析的对象的模型类。

    public class YourObjectModelClass{
       public String tag;
       public String sender;
       public String content;
    }
    
  3. 在categorizNotifications()中,您将替换代码:

    JSONObject json=new JSONObject(msg);
    Gson gson = new Gson();
    
    YourObjectModelClass model = gson.fromJson(json.toString(), YourObjectModelClass.class); //
    String tag = model.tag;
    if(tag.equals("comment"){
      String sender = model.sender;
      String content = model.content;
    }
    

    依旧......