反应原生json响应检查字符串或对象

时间:2017-10-16 01:34:21

标签: json react-native fetch

抱歉这个愚蠢的问题。我对原生的反应比较新。我有fetch工作,所以我可以从服务器返回json响应。如果出现错误,服务器API将返回一个字符串;如果成功,则返回一个json对象。有没有办法比较响应,看看它是一个字符串或json变量?

不确定如何实现上述任何帮助将不胜感激。

这是我的代码

API.js

    var API = {

   SetupBuyOnline(email, serialNumber, platformType) {
        var url = 'https://<urlomitted>/SetupBuyOnline';
        return fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json; charset=UTF-8',
                'Accept': 'application/json',
                'operating_system': platformType,
                'email': email,
                'serialNumber': serialNumber
            }
        }).then((res) => res.json());
    }
   };

找到userScreen.js

findUserScreen(){
// this.props.navigation.navigate('JoinNowScreen')
StudentApi.SetupBuyOnline('useremail@test.com', deviceId, "iOS")
.then((responseData) => {
  if(typeof(responseData) == 'string')
  {
    console.log('got api call ' + responseData);
    alert('test = ' + responseData);
  }
  else
  {
    console.log('got api call ' + responseData);
    alert(responseData);
  }
})

}

不确定我做错了什么。提前致谢

1 个答案:

答案 0 :(得分:4)

除了更改== ===(严格平等)之外,不要太多。但是会与正常的平等一起工作。

不知道你做错了什么,因为这段代码工作正常。

我要做的是获得JSON响应,如下所示:

"{
    error: true,
}"


"{
    error: false,
    data: yourDataSentByTheServer!
}"

这样你只需要检查你的JSON响应中是否有错误属性。

function stringType(){
  const responseData = 'hello';
  if(typeof(responseData) === 'string')
  {
    console.log('got api call ' + responseData);
    alert('test = ' + responseData);
  }
  else
  {
    console.log('got api call ' + responseData);
    alert(responseData);
  }
}

function objType(){
  const responseData = { 1:'hello', 2: 'koko' }
  if(typeof(responseData) === 'string')
  {
    console.log('got api call ' + responseData);
    alert('test = ' + responseData);
  }
  else
  {
    console.log('got api call ' + responseData);
    alert(responseData);
  }
}
<button onClick="stringType();">Click me for string</button>
<button onClick="objType();">Click me for obj</button>

相关问题