DroidScript wiki

(was AndroidScript) unofficial documentation by the community

User Tools

Site Tools


sample_code:json_funcs

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

sample_code:json_funcs [2015/04/01 07:41] (current)
stevegarman created
Line 1: Line 1:
 +====== JSON functions ======
 +I quite often find myself storing JSON representations of objects in files.
  
 +In order to simplify the coding slightly, I decided to write a couple of very simple functions.
 +
 +<code JavaScript funcs.js>​
 +function writeAsJson(path,​obj)
 +{
 +    app.WriteFile(path,​JSON.stringify(obj));​
 +}
 +
 +function readAsJson(path)
 +{
 +    if (app.FileExists(path))
 +      return JSON.parse(app.ReadFile(path));​
 +    app.ShowPopup(path+"​ does not exist"​);​
 +    return undefined;​
 +}
 +</​code>​
 +These can be used in an app like this
 +<code JavaScript funcsdemo.js>​
 +//​Called when application is started.
 +function OnStart()
 +{
 +    //​Create a layout with objects vertically centered.
 +    var lay = app.CreateLayout( "​linear",​ "​VCenter,​FillXY"​ );​    
 +
 +    //​Create a text label and add it to layout.
 +    var txt = app.CreateText( "​Hello"​ );​
 +    txt.SetTextSize(32);​
 +    lay.AddChild( txt );​
 +    
 +    //​Add layout to app.    
 +    app.AddLayout( lay );​
 +    test(txt);​
 +}
 +
 +function test(display)
 +{
 +   //​ file to store data 
 +   var fil="/​sdcard/​jsontest.txt";​
 +   //​build a test object
 +   var stuff = {"​value":​1,"​name":"​one"​};​
 +   //​save object in a file
 +   writeAsJson(fil,​stuff);​
 +   //​get copy of the object from the file
 +   var newobj = readAsJson(fil);​
 +   //​display data from the copy
 +   display.SetText(newobj.name +"​ is "​+ newobj.value);​
 +}
 +
 +function writeAsJson(path,​obj)
 +{
 +    app.WriteFile(path,​JSON.stringify(obj));​
 +}
 +
 +function readAsJson(path)
 +{
 +    if (app.FileExists(path))
 +      return JSON.parse(app.ReadFile(path));​
 +    app.ShowPopup(path+"​ does not exist"​);​
 +    return undefined;​
 +}
 +
 +</​code>​
sample_code/json_funcs.txt · Last modified: 2015/04/01 07:41 by stevegarman