react native json 响应检查字符串或对象

react native json response check if string or object

抱歉这个愚蠢的问题。我对原生反应还比较陌生。我已经获取工作,所以我可以从服务器返回 json 响应。如果有错误,服务器 API returns 一个字符串,如果成功则 returns 一个 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);
      }
    })
  }

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

除了将您的 == 更改为 ===(严格相等)外,没有太多变化。但将以正常的平等运作。

不知道你做错了什么,因为这段代码工作得很好。

我会做的是 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>