将包含JArray的JSON对象反序列化为C#对象

时间:2019-07-02 07:41:17

标签: c# json

我正在处理服务器-客户端应用程序。客户端有一个线程,他的主要目标是从服务器接收“房间状态”。

我的问题是将JSON数据包反序列化为C#对象。

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\"....]}"

上面的字符串是我从服务器收到的示例。 我该如何反序列化?

*我正在使用Newtonsoft.Json.Linq,但不仅限于此。

提前感谢您,安通

2 个答案:

答案 0 :(得分:1)

您可以为此目的使用Newtonsoft.Json

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

请在用C#命名类时,建议您使用Pascal Case,因此您的类应命名为RoomState

更新: 另外,请考虑通过以下方式构造将用于JSON序列化/反序列化的所有类:

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; }
}

答案 1 :(得分:1)

如果您不想污染属性的模型,也可以使用Fluent-JSON.NET

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    drawer.closeDrawers();
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

    switch (item.getItemId()) {
        case R.id.nav_announces:
            bottomNavigationView.setSelectedItemId(R.id.action_announces);
            ft.replace(R.id.f_container, mainFragment);
            break;
        case R.id.nav_account:
            bottomNavigationView.setSelectedItemId(R.id.action_account);
            ft.replace(R.id.f_container, accountFragment);
            break;
        case R.id.nav_sell:
            bottomNavigationView.setSelectedItemId(R.id.action_sell);
            ft.replace(R.id.f_container, sellFragment);
            break;
        case R.id.nav_chat:
            bottomNavigationView.setSelectedItemId(R.id.action_chat);
            ft.replace(R.id.f_container, chatFragment);
            break;
        case R.id.nav_notifications:
            bottomNavigationView.setSelectedItemId(R.id.action_notifications);
            ft.replace(R.id.f_container, notificationFragment);
            break;
    }

    ft.commit();
    return true;
}