无法在Unity中使用JSONUtility创建的Java脚本(节点JS-Express)中读取JSON数据

时间:2018-09-16 17:25:50

标签: json node.js express unity3d

这是我在Unity中的put请求:

UnityWebRequest request = UnityWebRequest.Put(baseUrl + "miniGame1s/", JsonUtility.ToJson(cardsToSend));

“ cardsToSend”是下面的对象表单类:

[Serializable]
class Cards
{
    public string uid;
    public List<Card> cards = new List<Card>();
}
[Serializable]
class Card
{
    public int index;
    public int theCard;
    public bool theAnswer;
    public int theState;
    public bool playerAnswer;
    public float answerMoment;
    public float timeAfterAnswer;
    public float scoreAfterAnswer;
    public int validOrNot;
}

这是用Node js和Express编写的服务器中的代码:

app.put('/api/miniGame1s',(req,res)=>{
    console.log(req.body);
    const objectSchema = Joi.object().keys({
        index: Joi.number().required(),
        theCard: Joi.number().required(),
        theAnswer: Joi.boolean().required(),
        theState: Joi.number().required(),
        playerAnswer: Joi.boolean().required(),
        answerMoment: Joi.number().required(),
        timeAfterAnswer: Joi.number().required(),
        scoreAfterAnswer: Joi.number().required(),
        validOrNot: Joi.number().integer().required()
    });
    const arraySchema = {
        uid: Joi.string().required(),
        cards: Joi.array().items(objectSchema)
    };

    const result = Joi.validate(req.body, arraySchema);
    if(result.error) return res.status(400).send(result.error.details[0].message);
    else{
        thatGame1InProgressIndex = game1sInProgress.findIndex(g => g.uid == req.body.uid);
        console.log('Index: ' + thatGame1InProgressIndex);
        for(let i = 0; i < req.body.cards.length;i++)
        {
            game1sInProgress[thatGame1InProgressIndex].cards[req.body.cards[i].index] = req.body.cards[i];
        }

        // TODO: validating incomming info and set the validation parameter

        // TODO: generate new cards and send them to client.
        let newCards = {
            uid: req.body.uid,
            cards: []
        };
        for(let i = 0; i < 10 ;i++)
        {
            let card = CreateACard(game1sInProgress[thatGame1InProgressIndex].cards[game1sInProgress[thatGame1InProgressIndex].cards.length-1].theCard, game1sInProgress[thatGame1InProgressIndex].cards.length);
            game1sInProgress[thatGame1InProgressIndex].cards.push(card);
            newCards.cards.push(card);
        }
        res.send(newCards);
    }
});

现在,服务器代码尚未完成。 (这不是问题) 问题是我无法在服务器中检索JSON对象。

我尝试了不同的方法,例如统一使用ToString()而不是JSON.ToJson(),或使用JSON.parse()解析服务器中的“ req.body”,或类似的方法。

在最佳情况下,我将给出错误:“ uid”为必填项 这就是Joi验证错误。这意味着它无法显示Object的参数。

我尝试使用POSTMAN应用程序将具有相同数据的相同请求发送到服务器。而且有效。

我认为问题在于JSONUtility产生的JSON结构就是问题。

任何帮助都会得到赞赏。

1 个答案:

答案 0 :(得分:1)

首先,我应该说这个链接非常有用:

UnityWebRequest.Post(url, jsonData) sending broken Json

解决方案是您需要将“内容类型”设置为“ application / json”。这样,Express可以实现JSON对象并完美读取它。为此,请在创建请求之后并将其发送到服务器之前添加以下行:

request.SetRequestHeader("Content-Type", "application/json");