如何在Parse中从JSON中创建一个特定类型的对象?

问题描述 投票:4回答:3

我有一个云代码脚本,可以从服务中提取一些JSON。该 JSON 包括一个对象数组。我想将这些对象保存到 Parse,但要使用特定的 Parse 类。我如何才能做到这一点?

这是我的代码。

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 parse-platform cloud-code
3个回答
6
投票

我想我知道该怎么做了。你需要将JSON数据对象中的className属性设置为你的类名。(在 源码)但我只在客户端尝试了一下。

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
}

1
投票

这个页面的例子 https:/parse.comdocsjsguide

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

1
投票

IHMO这个问题并不是重复的。如何使用Parse.Object fromJSON?[重复]

在这个问题中,JSON并不是由Parse.Object.toJSON函数本身生成的,而是来自另一个服务。

const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';   
Parse.Object.fromJSON(asJson);
// Without L3 this results into: 
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible 
© www.soinside.com 2019 - 2024. All rights reserved.