2012-05-03 69 views

回答

1

下面是一些與PlayN的JSON接口一起演示瞭如何使用存儲接口的代碼:

private void loadStoredData() { 
    // storage parameters 
    String storageKey = "jsonData"; 
    Json.Object jsonData = PlayN.json().createObject(); 

    // to reset storage, uncomment this line 
    //PlayN.storage().removeItem(storageKey); 

    // attempt to load stored data 
    String jsonString = PlayN.storage().getItem(storageKey); 

    // if not loaded, create stored data 
    if (jsonString == null) { 
     DemoApi.log("stored data not found"); 
     jsonData.put("firstWrite", new Date().toString()); 

    // else display data 
    } else { 
     jsonData = PlayN.json().parse(jsonString); 
     DemoApi.log("stored data loaded"); 
     DemoApi.log("data first written at " + jsonData.getString("firstWrite")); 
     DemoApi.log("data last read at " + jsonData.getString("lastRead")); 
     DemoApi.log("data last written at " + jsonData.getString("lastWrite")); 
    } 

    // update last read 
    jsonData.put("lastRead", new Date().toString()); 

    // write data (this works in Java -- not in HTML) 
    // see https://stackoverflow.com/q/10425877/1093087 
    /* 
    Json.Writer jsonWriter = PlayN.json().newWriter(); 
    jsonWriter.object(jsonData).done(); 
    jsonString = jsonWriter.write(); 
    */ 

    // alternative write routine 
    Json.Writer jsonWriter = PlayN.json().newWriter(); 
    jsonWriter.object(); 
    for (String key : jsonData.keys()) { 
     jsonWriter.value(key, jsonData.getString(key)); 
    } 
    jsonWriter.end(); 
    jsonString = jsonWriter.write(); 

    // store data as json 
    PlayN.storage().setItem(storageKey, jsonString); 

    // confirm 
    if (PlayN.storage().isPersisted()) { 
     DemoApi.log("data successfully persisted"); 
    } else { 
     DemoApi.log("failed to persist data"); 
    } 
} 

有一個與Json.Writer有點麻煩,似乎有點兒車,我docum在這個問題在這裏:In the HTML version of PlayN, why does the following JSON-handling code throw an exception?

相關問題