2010-09-14 69 views
9

我在Android上搜索了很多JSON解析,但不太相信。其实有一个简单的想法,但尚未清楚JSON解析。在Android中的JSON解析

如何在应用程序中实现JSON解析?

回答

17

这是一个非常简单的JSON字符串

{"key1":"value1","key2":"value2"} 

为了用它JSONObject这样获得的值:

JSONObject json_obj=new JSONObject(your json string); 
String value1=json_obj.getString("key1"); 
String value2=json_obj.getString("key2"); 

这是一个稍微复杂的json字符串

[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}] 

为了从这种使用中提取值JSONArray

JSONArray jArray=new JSONArray(your json string); 
for(int i=0;i<(jArray.length());i++) 
{ 
    JSONObject json_obj=jArray.getJSONObject(i); 
    String value1=json_obj.getString("key1"); 
    String value2=json_obj.getString("key2"); 
} 

希望这有助于有点...........

1

您可以使用SDK中捆绑的org.json软件包。

在这里看到:http://developer.android.com/reference/org/json/JSONTokener.html

+0

“JSONObject json = new JSONObject(jsonString);” – 2010-09-14 07:17:31

+0

“(jsonString)”用于上面的行中。 – 2010-09-14 07:18:17

+0

@david - 这是包含JSON编码信息的字符串。 – adamk 2010-09-14 07:34:41

3

您还可以检查出谷歌的GSON库here。 GSON用户指南here有一些有用的示例可帮助您入门。我发现GSON简单而强大。

1

另一个选择:使用杰克逊。

简单的用法;如果你有一个POJO绑定到:

ObjectMapper mapper = new ObjectMapper(); // reusable 
    MyClass value = mapper.readValue(source, MyClass.class); // source can be String, File, InputStream 
    // back to JSON: 
    String jsonString = mapper.writeValue(value); 

到地图:

Map<?,?> map = mapper.readValue(source, Map.class); 

或一棵树:(类似Android的org.json包提供哪些默认)

JsonNode treeRoot = mapper.readTree(source); 

以及更多的例子可以在http://wiki.fasterxml.com/JacksonInFiveMinutes找到。

与其他软件包相比的优点是它闪电般快;非常灵活和多功能(POJO,地图/列表,json树,甚至流解析器),并且正在积极开发。

0

本课程将构建JSON对象:

public class CreateJSON { 
    private JSONArray mStudArray; 
    private JSONObject mStudObject; 
    Student [] student=new Student[3] ; 
    public CreateJSON() { 

    } 

    public void initData() { 
     //date wirte in student array 
     student[0]=new Student(); 
     student[0].setmStudName("Vikas"); 
     student[0].setmPhoneNo("1234567890"); 
     student[0].setmRollNo(1); 

     student[1]=new Student(); 
     student[1].setmStudName("Rahul"); 
     student[1].setmPhoneNo("1234567890"); 
     student[1].setmRollNo(2); 

     student[2]=new Student(); 
     student[2].setmStudName("Raj"); 
     student[2].setmPhoneNo("1234567890"); 
     student[2].setmRollNo(3); 
    } 


    //student array converts to json array 
    public String writeDataTOJOSON() { 
     //JONS array created here 
     mStudArray=new JSONArray(); 
     initData(); 
     for(int i=0;i<3;i++) { 
      mStudArray.put(createJOSNObject(student[i])); 
     } 

     return mStudArray.toString(); 
    } 

    //student object converted into json object 
    public JSONObject createJOSNObject(Student student) { 



     try { 
      mStudObject=new JSONObject(); 
      mStudObject.put(Constants.NAME,student.getmStudName()); 
      mStudObject.put(Constants.PHONE_NUMBER,student.getmPhoneNo()); 
      mStudObject.put(Constants.ROLL_NUMBER,student.getmRollNo()); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return mStudObject; 
    } 
} 

//这个类将打印创建JSON

public class PrintJOSN { 
    private CreateJSON createJSON; 

    private JSONArray mStudnetArray; 




    public String printJSONData() { 


     createJSON=new CreateJSON(); 


     //JSONArray created here. 
     String jons=createJSON.writeDataTOJOSON(); 


     //JONS in String fomart 
     Logger.debug("json"+mStudnetArray); 

     //JOSN array create from string 
     try { 

      mStudnetArray=new JSONArray(jons); 
     } catch (JSONException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 



     //parse array parse here 
     for(int i=0;i<3;i++) { 
      try { 
       JSONObject studentObj=(JSONObject) mStudnetArray.get(i); 
       String name=studentObj.getString("name"); 
       String phone=studentObj.getString("phone_number"); 
       Integer rollnumber=studentObj.getInt("roll_number"); 

       Logger.debug("Student Object::: "+name+" "+phone+" "+rollnumber); 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 

     return null; 
    } 
} 

//主actvity

public class JSONParserActivity extends Activity { 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     PrintJOSN printJOSN=new PrintJOSN(); 
     printJOSN.printJSONData(); 

    } 
} 

学生模型:

public class Student { 

    private String mStudName; 

    private String mPhoneNo; 

    private Integer mRollNo; 

    public String getmStudName() { 
     return mStudName; 
    } 

    public void setmStudName(String mStudName) { 
     this.mStudName = mStudName; 
    } 

    public String getmPhoneNo() { 
     return mPhoneNo; 
    } 

    public void setmPhoneNo(String mPhoneNo) { 
     this.mPhoneNo = mPhoneNo; 
    } 

    public Integer getmRollNo() { 
     return mRollNo; 
    } 

    public void setmRollNo(Integer mRollNo) { 
     this.mRollNo = mRollNo; 
    } 


} 

恒类:

public class Constants { 
    public static final String NAME="name"; 
    public static final String ROLL_NUMBER="roll_number"; 
    public static final String PHONE_NUMBER="phone_number"; 
} 

Logger类:

public class Logger { 

    public static final String APP_ID = "androidapp"; 
    public static String logDir = "/androidapp"; 
    public static String logFileName = "/log.txt"; 
    public static boolean writeLogsToFile = false; 
    public static final int LOG_LEVEL_VERBOSE = 4; 
    public static final int LOG_LEVEL_DEBUG = 3; 
    public static final int LOG_LEVEL_INFO = 2; 
    public static final int LOG_LEVEL_ERROR = 1; 
    public static final int LOG_LEVEL_OFF = 0; 
    public static final int CURRENT_LOG_LEVEL = LOG_LEVEL_DEBUG; 

    public static void log(String message, int logLevel) { 
     if (logLevel > CURRENT_LOG_LEVEL) { 
      return; 
     } else { 
      Log.v(APP_ID, message); 
      if (writeLogsToFile) { 
       writeToFile(message); 
      } 
     } 
    } 

    private static void writeToFile(String message) { 
     try { 
      File sdCard = Environment.getExternalStorageDirectory(); 
      File dir = new File(sdCard.getAbsolutePath() + logDir); 
      dir.mkdirs(); 
      File file = new File(dir, logFileName); 
      PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file, true), 8 * 1024)); 
      writer.println(APP_ID + " " + new Date().toString() + " : " + message); 
      writer.flush(); 
      writer.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void verbose(String message) { 
     log(message, LOG_LEVEL_VERBOSE); 
    } 

    public static void debug(String message) { 
     log(message, LOG_LEVEL_DEBUG); 
    } 

    public static void error(String message) { 
     log(message, LOG_LEVEL_ERROR); 
    } 

    public static void info(String message) { 
     log(message, LOG_LEVEL_INFO); 
    } 
} 

请检查您的日志,它会显示创建JSON和JSON打印。