Anthon Naivelt
Anthon Naivelt

Reputation: 61

Deserialize JSON object containing JArray to C# object

I'm working on a Server-Client application. The Client has a thread that his main goal is receiving from the server the "room's state".

My problem is Deserializing the JSON packet to a C# object.

public class roomState //This is the class that I want to create
    {
        public int isActive { get; set; }
        public int questionCount { get; set; }
        public int answerTimeOut { get; set; }
        public JArray players { get; set; }
    }

string jsonObject = "{\"isActive\":<int>,\"questionCount\":<int>,\"answerTimeOut\":<int>,\"players\": [\"name1\",\"name2\",\"name3\"....]}"

the string above is an example of what I'm receiving from the server. How do I deserialize this?

*I'm using Newtonsoft.Json.Linq but not bound only to this.

Thank you in advance, Anthon

Upvotes: 0

Views: 749

Answers (2)

Alev Ryustemov
Alev Ryustemov

Reputation: 150

You can also use Fluent-JSON.NET if you do not want to pollute your models with attributes.

public class RoomStateMap: JsonMap < RoomState > {
  public RoomStateMap() {
    this.Map(x => x.isActive, "isActive");
    this.Map(x => x.questionCount, "questionCount");
    this.Map(x => x.answerTimeOut, "answerTimeOut");
    this.Map(x => x.players, "players");
  }
}

Upvotes: 1

zpouip
zpouip

Reputation: 787

You could use Newtonsoft.Json for this purpose:

public RoomState DeserializingMyRoomState()
{   
    string jsonObject = "{\"isActive\":<int>,\"questionCount\":<int>,\"answerTimeOut\":<int>,\"players\": [\"name1\",\"name2\",\"name3\"....]}";        
    RoomState myRoomState = JsonConvert.DeserializeObject<RoomState>(jsonObject);
    return myRoomState;
}

And please, when naming a class in C# I would suggest you to use Pascal Case, so your class should be named RoomState.

UPDATE: Also, consider structuring all your classes that would be used for JSON serialization/deserialization in the following way:

public class RoomState
{
      [JsonProperty("isActive")]
      public int IsActive { get; set; }

      [JsonProperty("questionCount")]
      public int QuestionCount { get; set; }

      [JsonProperty("answerTimeOut")]
      public int AnswerTimeOut { get; set; }

      [JsonProperty("players")]
      public List<string> Players { get; set; }
}

Upvotes: 1

Related Questions