Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
        }
    }
});
like image 262
TotoroTotoro Avatar asked Feb 12 '23 18:02

TotoroTotoro


1 Answers

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
}
like image 154
Immanuel Avatar answered Feb 14 '23 07:02

Immanuel