【问题标题】:react native json response check if string or object反应原生 json 响应检查字符串或对象
【发布时间】:2017-10-16 01:34:21
【问题描述】:

抱歉这个愚蠢的问题。我对原生反应比较陌生。我有 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);
      }
    })
  }

不知道我做错了什么。提前致谢

【问题讨论】:

    标签: json react-native fetch


    【解决方案1】:

    除了将您的== 更改为===(严格相等)之外不多。但是可以正常平等地工作。

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

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

    【讨论】:

    • 很奇怪。当我在它没有将其检测为字符串之前尝试过时。无论如何感谢您的帮助:)
    • 好吧 :) 但是考虑一下我的 JSON 选项,它是保持简洁的好方法 :)
    猜你喜欢
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    相关资源
    最近更新 更多