无法从START_OBJECT标记中反序列化String的实例

时间:2017-11-01 19:33:55

标签: php arrays json deserialization stringify

我已经完成了对这个问题的其他答案,但似乎没有人能够普遍应用它。其他问题没有答案。

显然,我得到"无法从START_OBJECT令牌中反序列化String的实例。"在我的控制台中。我相信当我尝试从我的websocketdata中进行字符串化(响应)时会发生这种情况。

这是代码。

    <?php /**
 * The Header for our theme.
 *
 * Displays all of the <head> section and everything up till <div id="main">
 *
 */ ?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
    <!--<![endif]-->
    <head>
        <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
        <script type="text/javascript"
          src='http://martialparks.com/wp-content/themes/js/gamesparks-rt.js'></script>
        <script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/gamesparks.js'></script>
        <script type='text/javascript'
          src='http://martialparks.com/wp-content/themes/js/gamesparks-functions.js'></script>
        <script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/hmac-sha256.js'></script>
        <link rel="profile" href="http://gmpg.org/xfn/11" />
        <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
        <?php
        wp_head();
        ?>
    </head>

    <body <?php body_class() ?>>
        <body onload="init()">
        <!--Start Header Wrapper-->
        <div class="header_wrapper">
            <div class="header">
                <!--Start Container-->
                <div class="container_24">
                    <div class="grid_24">
                        <div class="logo"> <a href="<?php echo esc_url(home_url()); ?>"><img src="<?php if (business_directory_get_option('business_directory_logo') != '') { ?><?php echo esc_url(business_directory_get_option('business_directory_logo')); ?><?php
                                } else {
                                    echo esc_url(get_template_directory_uri() . '/images/logo.png');
                                }
                                ?>" alt="<?php bloginfo('name'); ?>" /></a></div>
                    </div>
                    <div class="clear"></div>
                </div>
                <!--End Container-->
                <div class="clear"></div>
            </div>
            <div class="clear"></div>
            <!--Start Menu Wrapper-->
            <div class="menu_wrapper">
                <div class="top_arc"></div>
                <div class="menu-container">
                    <div class="container_24">
                        <div class="grid_24">
                            <?php business_directory_nav(); ?> 
                        </div>
                    </div>
                    <div class="clear"></div>
                </div>
                <div class="clear"></div>
                <div class="bottom_arc"></div>
            </div>
            <!--End Container-->
            <div class="clear"></div>
        </div>
        <!--End Header Wrapper-->
        <div class="clear"></div>
        <div class="wrapper">
            <!--Start Container-->
            <div class="container_24">
                <div class="grid_24">
                <br/>
                <br/>
                <br/>
                  <input id="apiKey" type="hidden" value="A319082inSk2"/>
                  <input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
                  <label for="apiCredential">Api Credential</label><input id="apiCredential"/>
                  <label for="username">User Name</label><input id="username"/>
                  <label for="password">Password</label><input id="password"/>
                  <button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
                    <button onClick='gamesparks.authenticationRequest(username, password, loginResponse)'>Login</button>
                    <button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
                    <button onClick='customEvent()'>Custom Event</button>
                    <button onClick='testRT()'>Test RT</button>
                  <i>Special thanks to the awesome team at GameSparks!</i>
                  <div id="messages"></div>
                  <br/>
                  <br/>


User Name
<div id="displayName" style="color: blue;"></div>
Coins
<div id="Coins" style="color: red;"></div>
Exp
<div id="Exp" style="color: green;"></div>
Leader Points
<div id="LeadP" style="color: darkgreen;"></div>
Hero Points
<div id="HeroP" style="color: purple;"></div>

                <style>
                    #map {
                    height: 400px;
                    width: 100%;
                    }
                </style>

                <h3>Find a Park</h3>
                    <div id="map"></div>
                    <script>
                      function initMap() {
                        var Velocity = {lat: 38.308101, lng: -85.815464};
                        var map = new google.maps.Map(document.getElementById('map'), {
                          zoom: 4,
                          center: Velocity
                        });
                        var marker = new google.maps.Marker({
                          position: Velocity,
                          map: map
                        });
                      }
                    </script>
                    <script async defer
                    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDSHCinT3IVWFCLUudbsMZV6644GNrGiwc&callback=initMap">
                    </script>



<script type="text/javascript">

  //Create a gamesparks object to be used
  var gamesparks = new GameSparks();

  //Initialse the SDK
  function init() {
    gamesparks.initPreview({
      key: document.getElementById('apiKey').value,
      secret: document.getElementById('apiSecret').value,
      credential: document.getElementById('apiCredential').value,
      onNonce: onNonce,
      onInit: onInit,
      onMessage: onMessage,
      logger: console.log,
    });
  }

  function accountDetailsResponseCreator() {
    var response = {
      displayName: 'A User',
      currencies: {Coins: 'A coin', Exp: 'A exp', LeadP: 'A lead p', HeroP: 'A hero p'}
    }
    accountDetailsResponse(response)
  }

  //Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
  function onNonce(nonce) {
    return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
  }

  //Callback to handle when the SDK is initialised and ready to go
  function onInit() {
    console.log("Initialised");
  }

  //Callback to handle async messages from the gamesparks platform
  function onMessage(message) {
    console.log("onMessage");
  }

  //Response handler examples
  function registerResponse(response) {
    console.log(JSON.stringify(response));
  }

  function loginResponse(response) {
    console.log(JSON.stringify(response));
  }

  function accountDetailsResponse(response) {
    console.log (JSON.stringify(response));//logs the string to console
    document.getElementById("displayName").innerHTML = (response.displayName);
    document.getElementById("Coins").innerHTML = (response.currencies.Coins);
    document.getElementById("Exp").innerHTML = (response.currencies.Exp);
    document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
    document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string.  I've tried doing each line with semicolons at the end, and all in a group with commas separating them.  Both just give me the first variable and delete the rest.
  }

  function customEvent() {
    gamesparks.sendWithData(
      "LogEventRequest",
      {
        eventKey: "FIRST_EVENT",
        NUMBER_ATTR: 123,
        STRING_ATTR: "this is a string",
        JSON_ATTR: {key1: 12, key2: "abc"}
      },
      function (response) {
        console.log(JSON.stringify(response));
      }
    );
  }

  var apiKey = "2974660weiMa";
  var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
  var myTimer = null;
  var myRTSession = function () {
  };
  var numCycles = 0;

  myRTSession.started = false;
  myRTSession.onPlayerConnectCB = null;
  myRTSession.onPlayerDisconnectCB = null;
  myRTSession.onReadyCB = null;
  myRTSession.onPacketCB = null;
  myRTSession.session = null;

  myRTSession.start = function (connectToken, host, port) {
    var index = host.indexOf(":");
    var theHost;

    if (index > 0) {
      theHost = host.slice(0, index);
    } else {
      theHost = host;
    }

    console.log(theHost + " : " + port);

    myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
    if (myRTSession.session != null) {
      myRTSession.started = true;

      myRTSession.session.start();
    } else {
      myRTSession.started = false;
    }
  };

  myRTSession.stop = function () {
    myRTSession.started = false;

    if (myRTSession.session != null) {
      myRTSession.session.stop();
    }
  };

  myRTSession.log = function (message) {
    var peers = "|";

    for (var k in myRTSession.session.activePeers) {
      peers = peers + myRTSession.session.activePeers[k] + "|";
    }

    console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
  };

  myRTSession.onPlayerConnect = function (peerId) {
    myRTSession.log(" OnPlayerConnect:" + peerId);

    if (myRTSession.onPlayerConnectCB != null) {
      myRTSession.onPlayerConnectCB(peerId);
    }
  };

  myRTSession.onPlayerDisconnect = function (peerId) {
    myRTSession.log(" OnPlayerDisconnect:" + peerId);

    if (myRTSession.onPlayerDisconnectCB != null) {
      myRTSession.onPlayerDisconnectCB(peerId);
    }
  };

  myRTSession.onReady = function (ready) {
    myRTSession.log(" OnReady:" + ready.toString());

    if (myRTSession.onReadyCB != null) {
      myRTSession.onReadyCB(ready);
    }
  };

  myRTSession.onPacket = function (packet) {
    myRTSession.log(" OnPacket:" + packet.toString());

    if (myRTSession.onPacketCB != null) {
      myRTSession.onPacketCB(packet);
    }
  };

  function testRT() {
    myRTSession.stop();

    gamesparks.initPreview({
      key: apiKey,
      secret: apiSecret,
      credential: "",
      onNonce: onNonceRT,
      onInit: onInitRT,
      onMessage: onMessageRT,
      logger: console.log,
    });
  }

  function onNonceRT(nonce) {
    return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
  }

  function onInitRT() {
    console.log("Initialised");

    gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function (response) {
      if (response.error) {
        console.error(JSON.stringify(response.error));
      } else {
        sendMatchmakingRequest();
      }
    });
  }

  //Callback to handle async messages from the gamesparks platform
  function onMessageRT(message) {
    //console.log("message " + JSON.stringify(message));
    if (message["@class"] === ".MatchFoundMessage") {
      var accessToken = message["accessToken"];
      var host = message["host"];
      var port = message["port"];

      myRTSession.stop();

      if (myTimer) {
        clearTimeout(myTimer);
      }

      myTimer = setInterval(mainRTLoop, 10);

      myRTSession.start(accessToken, host, port);
    } else if (message["@class"] === ".MatchNotFoundMessage") {
      console.log("MATCH NOT FOUND");

      sendMatchmakingRequest();
    }
  }

  function sendMatchmakingRequest() {
    gamesparks.sendWithData("MatchmakingRequest",
      {
        skill: 1,
        matchShortCode: "Match_STD"
      },
      function (response) {
        if (response.error) {
          console.error(JSON.stringify(response.error));
        } else {
          console.log("Match OK...");
        }
      }
    );
  }

  function mainRTLoop() {
    if (myRTSession.started) {
      myRTSession.session.update();

      var data = RTData.get();

      data.setLong(1, numCycles);

      myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);

      numCycles++;
    }
  }
</script>
</body>
</html>

对于我的生活,我不知道发生了什么或如何解决它。当我激活一个引用第173行的按钮时,会弹出问题 function loginResponse(response) { console.log(JSON.stringify(response)); }

但不要让这影响你的公正性。我将此代码与我的代码的早期版本进行了比较,并且无法识别我的任何函数的更改。

1 个答案:

答案 0 :(得分:0)

嗯,最重要的是:当你是白痴时,不要向stackoverflow发帖。没有人会回应。不是因为它们是卑鄙的,而是因为学习基础知识很重要。

所以问题源于我的代码顶部:

        <button onClick='gamesparks.authenticationRequest(username, password, loginResponse)'>Login</button>

很奇怪,对吗?并不是的。做了什么是尝试改变身份验证请求的输入以匹配我的html元素输入(请参阅我的元素被标记为用户名和密码?)它没有用,我显然只是把它搁置并继续...并忘记了。我所做的是将“用户名”更改为“testuser”。这与我尝试验证的值相匹配。现在,我的宝宝正在我的testuser上返回值,并像梦一样运行。

感谢艰难的爱,stackoverflow。