【问题标题】:How to create an object of specific type from JSON in Parse如何在 Parse 中从 JSON 创建特定类型的对象
【发布时间】:2014-12-15 21:11:00
【问题描述】:

我有一个从服务中提取一些 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 parse-cloud-code


    【解决方案1】:

    我想我成功了。您需要将 JSON 数据对象中的 className 属性设置为您的类名。 (在source code 中找到)但我只在客户端尝试过。

    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】:

    来自此页面的示例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.
      }
    });
    

    【讨论】:

      【解决方案3】:

      IHMO 这个问题不是How to use Parse.Object fromJSON? [duplicate]的重复问题

      在这个问题中,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 
      

      【讨论】:

        猜你喜欢
        • 2016-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-24
        • 1970-01-01
        • 1970-01-01
        • 2010-09-16
        • 2015-11-02
        相关资源
        最近更新 更多