如何从解析中的JSON创建特定类型的对象

问题描述:

我有一个Cloud Code脚本,可以从服务中提取一些JSON.该JSON包含一个对象数组.我想将它们保存到Parse,但是使用特定的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?

这是我的代码.

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?
        }
    }
});

我认为我可以使用它.您需要将JSON数据对象中的className属性设置为您的类名称. (在源代码中找到它) ),但我只在客户端上尝试过此操作.

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
}