读写json文件

时间:2018-04-30 16:12:11

标签: android

此方法从json文件中读取文本。我想从json文件中只读取名称,日期,时间。我怎样才能完成此操作。我的json文件包含各种记录,每条记录包含name,lat,lon,image_name,date ,time.I需要读取一个记录的名称,日期,时间并将其作为单选按钮1的值,然后读取第二个记录的第二个名称,日期,时间,并将其置于无线电的butto2值。 我还需要删除特定名称并更新特定名称。 请帮助我,并提前感谢您。祝您有个美好的一天。

 String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
            File myDir = new File(root + "/GeoPark");//create folder in internal storage
            myDir.mkdirs();// make directory
            File file = new File(myDir, FILENAME);//making a new file in the folder

            if(file.exists())   // check if file exist
            {
                //Read text from file
                StringBuilder text = new StringBuilder();

                try {
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = br.readLine()) != null) {
                        text.append(line);
                    }
                }
                catch (IOException e) {
                    //You'll need to add proper error handling here
                }
                //Set the text
                String x=text.toString();
                String z=x.replace("{","").replace("date:","").replace("time:","").replace("Record:","").replace("[","").replace("latitude:","").replace("longitude:","").replace("name:","").replace("address:","").replace("pin:","").replace("area:","").replace("image:","").replace("\"","").replace("]","").replace("}","");
                String[] y=z.split(",");

                rb1.setText(y[3].toString()+","+y[7].toString()+","+y[8].toString());

            }
            else
            {
                rb1.setText("Sorry file doesn't exist!!");
            }

这是我的json文件

{Record:["lat":"22.5835","lon":"88.456","name":"aa","add":"cc",date:30/04/2018,time:21:05:10]}
{Record:["lat":"22.583544","lon":"88.45642","name":"BB","add":"cc",date:30/04/2018,time:21:05:40]}

3 个答案:

答案 0 :(得分:0)

考虑使用GSON。

序列化就像调用

一样简单
type FileSearcher struct {
    Contents []MyFile
}

func (fe *FileSearcher) FindFileRecursive(searchPath, namePattern string) (err error) {

    // get absolute path
    if searchPath, err = filepath.Abs(searchPath); err != nil {
        return
    }
    curFileName := filepath.Base(searchPath)
    if matched, err := filepath.Match(namePattern, curFileName); err == nil && matched {
        if foundFile, err := NewFileFromPath(searchPath); err == nil {
            fe.Contents = append(fe.Contents, *foundFile) // found a match
        }
    } else {
        return
    }

    if isDir, _ := utils.IsDirectory(searchPath); isDir {
        if files, err := ioutil.ReadDir(searchPath); err == nil {
            for _, f := range files {
                fPath := filepath.Join(searchPath, f.Name())
                go fe.FindFileRecursive(fPath, namePattern) // recursive in a goroutine here
            }
        }
    }
    return
}

// FindFile searches for files/directories matching namePattern under searchPath
func (fe *FileSearcher) FindFile(searchPath, namePattern string) (err error) {

    queue := make([]string, 0)
    queue = append(queue, searchPath)

    for len(queue) > 0 {
        path := queue[0]
        curFileName := filepath.Base(path) // get the file/directory name at this path
        queue = queue[1:]                  // pop off the head

        if matched, err := filepath.Match(namePattern, curFileName); err == nil && matched {
            if foundFile, err := NewFileFromPath(path); err == nil {
                fe.Contents = append(fe.Contents, *foundFile) // found a match
            }
        }

        if isDir, _ := utils.IsDirectory(path); isDir {
            if files, err := ioutil.ReadDir(path); err == nil {
                for _, f := range files {
                    fPath := filepath.Join(path, f.Name())
                    queue = append(queue, fPath) // push the new dir path to queue
                }
            }
        }
    }
    return
}

对于反序列化,

String jsonStr = Gson().toJson(obj)

JSON on Android - serialization

答案 1 :(得分:0)

首先,你应该将你的字符串转换为json对象,然后根据需要解析它。

假设你的json是

String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}";

然后你可以轻松做到

JSONObject json = (JSONObject) JSONSerializer.toJSON(data);        
    double coolness = json.getDouble( "coolness" );
    int altitude = json.getInt( "altitude" );
    JSONObject pilot = json.getJSONObject("pilot");
    String firstName = pilot.getString("firstName");
    String lastName = pilot.getString("lastName");

    System.out.println( "Coolness: " + coolness );
    System.out.println( "Altitude: " + altitude );
    System.out.println( "Pilot: " + lastName );

难道不容易吗?

答案 2 :(得分:0)

在这里,试试这个

String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
            File myDir = new File(root + "/GeoPark");//create folder in internal storage
            myDir.mkdirs();// make directory
            File file = new File(myDir, FILENAME);//making a new file in the folder

            if(file.exists())   // check if file exist
            {
                //Read text from file
                StringBuilder text = new StringBuilder();

                try {
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = br.readLine()) != null) {
                        text.append(line);
                    }
                }
                catch (IOException e) {
                    //You'll need to add proper error handling here
                }
                //Set the text


            JSONObject obj = new JSONObject(text.toString());
            JSONArray arr = obj.getJSONArray("Record");
            for (int i = 0; i < arr.length(); i++){
                 String name = arr.getJSONObject(i).getString("name");
                 String date = arr.getJSONObject(i).getString("date");
                 String time = arr.getJSONObject(i).getString("time");
              }
            }
            else
            {
                rb1.setText("Sorry file doesn't exist!!");
            }

你也可以看到 - &gt; http://theoryapp.com/parse-json-in-java/