0

What I'm trying to Do is getting a Json with .Net.WebSockets and parse it with Simple Json, however I face the error "Json format seems invalid".
at first i suspected json that is coming from server might be invalid but after some investigation i tried to parse the exact json from file not from server and it was ok , so i think there must be something wrong in my code but i can't seem to find it ( I'm new to websockets ).

 public async void StartMatch()
{
    await ConnectToServer();
    await SendMassage();
    FoundPlayer(await GetMassage());
}

 public void FoundPlayer(string oppInfo)
{
    Debug.Log(oppInfo);
    JSONNode node = JSON.Parse(oppInfo);

}

public async Task SendMassage()
{
    JSONNode node = JSON.Parse(json);
    node["data"]["categoryId"].AsInt = readyToPlay.id;
    string id = node.ToString();
    var encoded = Encoding.UTF8.GetBytes(id);
    var buffer = new ArraySegment<byte>(encoded, 0, encoded.Length);
    await Task.Run(() => ws.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None));
    Debug.Log("Sent");
}

public async Task<string> GetMassage()
{
    byte[] bufferSize = new byte[5000];
    var buffer = new ArraySegment<byte>(bufferSize, 0, bufferSize.Length);
    var results = await Task.Run(() => ws.ReceiveAsync(buffer, CancellationToken.None));
    string bufferResult = Encoding.Default.GetString(buffer.Array);
    wait.SetActive(false);
    Debug.Log("Received");
    return bufferResult;

}

and here is Json if you need it.

{
   "action":"MatchStart",
   "message":{
      "opponentInfo":{
         "firstName":"James",
         "lastName":"Newell",
         "username":"JN",
         "image":null,
         "level":0,
         "cityName":null,
         "provinceName":null
      },
      "question":{
         "id":142570,
         "text":"کمپانی «گوگل» متعلق به کدام کشور میباشد؟",
         "image":"",
         "audio":"",
         "options":[
            {
               "id":715538,
               "option":"ایتالیا"
            },
            {
               "id":715536,
               "option":"آمریکا"
            },
            {
               "id":715539,
               "option":"بریتانیا"
            },
            {
               "id":715537,
               "option":"آلمان"
            }
         ]
      },
      "questionIndex":1,
      "questionsCount":7,
      "gameToken":"9d545d801bffe656a9140a877b050210",
      "validTime":10,
      "userId":75714
   }
}
Raminlich
  • 45
  • 7
  • In general there is no such field called `"data"` nor `"categoryId"` anywhere in your JSON you show us here ... so what exactly did you expect? And then not sure but is it possible simple json doesn't play well with the Arabic symbols? – derHugo May 16 '21 at 18:13
  • howdy, do not use "simpleJSON" or anything else. They are rubbish. **JSON is now built in to Unity** https://stackoverflow.com/a/38535392/294884 – Fattie May 16 '21 at 18:17
  • Does this answer your question? [What's the best way to loop through a JSON of sales data to create a graph in Unity?](https://stackoverflow.com/questions/38535239/whats-the-best-way-to-loop-through-a-json-of-sales-data-to-create-a-graph-in-un) – Fattie May 16 '21 at 18:17
  • @Fattie they are not ;) they are made for a specific use case and work pretty well on it ^^ – derHugo May 16 '21 at 18:18
  • Also what is the exact reason for first parsing the JSON into a node and then again use `node.ToString()` ? – derHugo May 16 '21 at 18:18
  • @derHugo I appreciate what you mean. but a beginner or hobbyist trying Unity should simply use the completely available, totally built-in system. there's just no reason at all in that situation and for such a trivial use case to do anything other than use the totally built-in, simple, system, IMO – Fattie May 16 '21 at 18:20
  • @derHugo data or categoryId is for sending i'm having problem with receiving and parsing – Raminlich May 16 '21 at 18:23
  • 2
    @Fattie yes, but please don't promote your biased answers but rather link to a way more complete and sophisticated like [Serialize and Deserialize Json and Json Array in Unity](https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity) ;) – derHugo May 16 '21 at 18:24
  • @Raminlich but aren't you sending the same json there? You are using `node.ToString` .. shouldn't that return the same value as `json` ? So either there are fields missing or I understand something completely wrong in your code .. – derHugo May 16 '21 at 18:25
  • @derHugo no they are not same – Raminlich May 16 '21 at 18:26
  • @derHugo I don't think there is a problem with arabic characters – Raminlich May 16 '21 at 18:27

1 Answers1

0

the issue was from GetMassage Function I was trying to extract Json from buffer which resulted invalid json I don't know exactly why , tried to assign ReceiveAsync to WebSocketReceiveResult through this code :

    public async Task<string> GetMassage()
{
    byte[] bufferSize = new byte[5000];
    var buffer = new ArraySegment<byte>(bufferSize, 0, bufferSize.Length);
    var results = await Task.Run(() => ws.ReceiveAsync(buffer, CancellationToken.None));
    string bufferResult = Encoding.Default.GetString(buffer.Array , buffer.Offset,results.Count);
    wait.SetActive(false);
    Debug.Log("Received");
    return bufferResult;

}

Now problem is solved and i no longer get invalid json

Raminlich
  • 45
  • 7