Home > database >  JSON Deserialization for dictionary with arrays
JSON Deserialization for dictionary with arrays

Time:12-15

I have a Python code that sends this JSON through MQTT.

message = {
        "name":"Alex",
        "date": 2021,
        "activity":["act1","act2","act3"],
        } 

Then I receive and Deserialize it in a C# script

public void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
    { 
          var Message = System.Text.Encoding.Default.GetString(e.Message);
          Dictionary<string, string> MessageDICT = JsonConvert.DeserializeObject<Dictionary<string, string>>(Message);
    }

The keys "name" and "date" has no problem being deserialized into the dictionary. However the error comes with "activity" due it being an array. Where it states "Unexpected character encountered while parsing value:[". I have seen methods where they deserialize it separately (where the array is sent in a different message), however this is not what I want. Is there a way I can deserialize the message as a whole?

Thanks.

CodePudding user response:

You have your dictionary declared as <string, string>, but "activity" is an array. So this is why it does not work.

If you want to keep using a dictionary, then you can instead declare it as <string, object> and then it will work for any type of data. But you will need to then check what Type it is before you later try to use it.

Dictionary<string, object> MessageDICT = JsonConvert.DeserializeObject<Dictionary<string, object>>(message);

You can then access it like this:

object first = ((JArray)MessageDICT["activity"])[0];

But if possible, you should try to use a fixed class for the data and deserialize that. Otherwise, maybe a dynamic is better.

CodePudding user response:

Hi why not use a class to read the json

public class Message
{
  public string name {get;set;}
  public string date {get;set;} //actually, this looks like an int the json, however...
  public string[] activity {get;set;}
}

usage

var res = JsonConvert.DeserializeObject<Message>(message);
  • Related