ファイルへの書き込み時にJSONObjectsを追加

CoffeeBreak:

私が追加しようとしているJSONObjectsと呼ばれるJSONArray内Records

私はそれを保存する最初の時間は、それは大丈夫です、このように保存します

{
  "Records": [
    {
      "travelTime": 2,
      "totalDistance": 0,
      "pace": 0,
      "kCalBurned": 0,
      "latlng": "[lat\/lng: (-32.1521234,-63.66412321)]"
    }
  ]
}

私は再びレコード内に新しいjsonobjectを追加しようとする。しかし、それはそれのために新しいJSONArrayを作成し、私はちょうど、レコード内の新しいオブジェクトを追加したいです

{
  "Records": [
    {
      "travelTime": 2,
      "totalDistance": 0,
      "pace": 0,
      "kCalBurned": 0,
      "latlng": "[lat\/lng: (-31.6432292,-63.3667462)]"
    }
  ]
}{
  "Records": [
    {
      "travelTime": 1,
      "totalDistance": 0,
      "pace": 0,
      "kCalBurned": 0,
      "latlng": "[lat\/lng: (-31.9522431,-64.3461241)]"
    }
  ]
}

これは私が保存するために使用するコードです Records

   private void writeJsonData(long travelTime,float totalDistance, float pace, float kCalBurned, LinkedList<LatLng> latlng){

        String jsonStr = "";
        JSONObject records  = new JSONObject();
        try {
            records.put("travelTime", travelTime);
            records.put("totalDistance", totalDistance);
            records.put("pace", pace);
            records.put("kCalBurned", kCalBurned);
            records.put("latlng", latlng);

            JSONArray jsonArray = new JSONArray();
            jsonArray.put(records);

            JSONObject recordsObj = new JSONObject();
            recordsObj.put("Records", jsonArray);

            jsonStr = recordsObj.toString();

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String file_name = "records.json";

        FileOutputStream fileOutputStream = null;
        try {

            fileOutputStream = new FileOutputStream(new File(mContext.getFilesDir(),file_name),true);
            fileOutputStream.write(jsonStr.getBytes());
            fileOutputStream.close();


        } catch (IOException e) {
            e.printStackTrace();
        }


    }
アリAhsan:

第二のパラメータを渡すtrueにはFileOutputStream、コンストラクタは、ファイルの末尾にjsonObjectを追加します。

内部のJSON配列でそれを追加するにはRecords、オブジェクト、あなたは、最初のファイルを読み込み、新しいJSONオブジェクトを追加し、バックファイルにそれを書くためにきました。

使用GSONの Javaクラス&JSONとの間の変換のためのライブラリ。だから、それぞれの鍵ペアを置くことによって、手動で毎回JSONオブジェクトを作成する必要はありません。

全体を保持するためのJavaクラスを作成しRecords、オブジェクトを

public class Record
{
    @SerializedName("Records")
    private List<Object> recordsList;

    public Record()
    {
        this. recordsList = new ArrayList<>();
    }

    public List<Object> getRecordsList()
    {
        return recordsList;
    }
}

今作成JAVA Model class旅行情報を保持します

public class Travel {

    private Integer travelTime;
    private Integer totalDistance;
    private Integer pace;
    private Integer kCalBurned;
    private LinkedList<LatLng> latlng;

    public Integer getTravelTime() {
        return travelTime;
    }

    public void setTravelTime(Integer travelTime) {
        this.travelTime = travelTime;
    }

    public Integer getTotalDistance() {
        return totalDistance;
    }

    public void setTotalDistance(Integer totalDistance) {
        this.totalDistance = totalDistance;
    }

    public Integer getPace() {
        return pace;
    }

    public void setPace(Integer pace) {
        this.pace = pace;
    }

    public Integer getKCalBurned() {
        return kCalBurned;
    }

    public void setKCalBurned(Integer kCalBurned) {
        this.kCalBurned = kCalBurned;
    }

    public LinkedList<LatLng> getLatlng() {
        return latlng;
    }

    public void setLatlng(LinkedList<LatLng> latlng) {
        this.latlng = latlng;
    }

}

ここでは内部の新しいJSONを追加する機能を持つユーティリティクラスであるRecordsオブジェクトが。ディレクトリ&ファイルがそれ以外に作成される場合はboth.Ifファイルが存在を作成し、それは、ファイルを読み込むリストに新しいJSONオブジェクトを追加し、バック同じファイルにそれを書き込みますチェックします。あなたはあなたのディレクトリ&ファイル名を変更することができます。

注意:このクラスは、Kotlinで書かれています。ここで参照されるかKotlinのセットアップのAndroid Studioには、

class Logger {

    companion object {

        private const val LOG_FILE_FOLDER = "Logs"
        private const val LOG_FILE_NAME = "transaction"
        private const val DATE_FORMAT = "yyyy-MM-dd"
        private val logFileName: String
            @SuppressLint("SimpleDateFormat")
            get() {

                var fileName = LOG_FILE_NAME
                val dateFormat = SimpleDateFormat(DATE_FORMAT)
                fileName += "_" + dateFormat.format(Date()) + ".json"
                return fileName
            }

fun logFile(json: Any) {

try {
    val directoryPath = Environment.getExternalStorageDirectory().path + "/" + LOG_FILE_FOLDER
    val loggingDirectoryPath = File(directoryPath)
    var loggingFile = File("$directoryPath/$logFileName")
    if (loggingDirectoryPath.mkdirs() || loggingDirectoryPath.isDirectory) {
        var isFileReady = true
        var isNewFile = false
        if (!loggingFile.exists()) {
            isFileReady = false
            try {
                loggingFile.createNewFile()
                isNewFile = true
                isFileReady = true
            } catch (e: Exception) {
                e.printStackTrace()
            }

        } else {
            val lastFile = getLastFile(loggingFile.name, directoryPath)
            loggingFile = File("$directoryPath/$lastFile")
            val fileSize = getFileSize(loggingFile)

        }
        if (isFileReady) {

            var jsonString: String? = null

            if (!isNewFile) {

                //Get already stored JsonObject
                val stream = FileInputStream(loggingFile)


                try {
                    val fileChannel = stream.channel
                    val mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size())

                    jsonString = Charset.defaultCharset().decode(mappedByteBuffer).toString()
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    stream.close()
                }
            }


            //Create record object
            val record = if (!jsonString.isNullOrEmpty()) {
                Gson().fromJson(jsonString, Record::class.java)
            } else {
                Record()
            }


            //Append the current json
            record.recordList.add(json)

            //create json to save
            val jsonToSave = Gson().toJson(record)

            val bufferedOutputStream: BufferedOutputStream
            try {
                bufferedOutputStream = BufferedOutputStream(FileOutputStream(loggingFile))
                bufferedOutputStream.write(jsonToSave.toByteArray())
                bufferedOutputStream.flush()
                bufferedOutputStream.close()

            } catch (e4: FileNotFoundException) {
                e4.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                System.gc()
            }
        }
    }
} catch (ex: Exception) {
    ex.printStackTrace()
}
}
}
}

最後には、あなたが持つファイルログインすることができますlogFile方法を

Logger.Companion.logFile(travel);

乾杯:)

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=207585&siteId=1