How to create an object of specific type from JSON in Parse

回眸只為那壹抹淺笑 提交于 2019-12-31 00:45:52

问题


I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?

Here's my code.

Parse.Cloud.httpRequest({
    url: 'http://myservicehost.com', 
    headers: {
        'Authorization': 'XXX'
    },
    success: function(httpResponse) {
        console.log("Success!");

        var json = JSON.parse(httpResponse.text);
        var recipes = json.results;

        for(int i=0; i<recipes.length; i++) {
                var Recipe = Parse.Object.extend("Recipe");
                var recipeFromJSON = recipes[i];
                // how do i save recipeFromJSON into Recipe without setting all the fields one by one?
        }
    }
});

回答1:


I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.

for(int i=0; i<recipes.length; i++) {
    var recipeFromJSON = recipes[i];
    recipeFromJSON.className = "Recipe";
    var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
    // do stuff with recipeParseObject
}



回答2:


Example from this page https://parse.com/docs/js/guide

var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();

gameScore.save({
  score: 1337,
  playerName: "Sean Plott",
  cheatMode: false
}, {
  success: function(gameScore) {
    // The object was saved successfully.
  },
  error: function(gameScore, error) {
    // The save failed.
    // error is a Parse.Error with an error code and message.
  }
});


来源:https://stackoverflow.com/questions/26473226/how-to-create-an-object-of-specific-type-from-json-in-parse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!