JSON: what is the equivalent of java Map in C #

I ran into a problem that using JSON to transfer an object to C # and C # passes the string back to Java and then java deserializes it to the BTW card, version .net 3.5

Here is the problem

The Java JSON string is shown in this format:

{"key1":"value1","key2":"value2"} 

but in C # the dictionary is seralized to

 [{"Key":"key1","Value":"value1"},{"Key":"key2","Value":"value2"}] 

I just want to find a way to do this:

  • for a java card JSON format, C # can characterize it
  • for C #, find a way to serialize it in a Java-friendly format

thanks

+4
source share
2 answers

Try using a JavaScriptSerializer instead of a DataContractJsonSerializer :

 var dict = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; var jss = new JavaScriptSerializer(); string json = jss.Serialize(dict); // {"key1":"value1","key2":"value2"} 
+5
source

I wrote a dictionary extension method for serializing it in JSON:

 public static string SerializeToJson(this IDictionary<string, object> dict) { var sb = new StringBuilder(); sb.Append("{"); foreach (string key in dict.Keys) { sb.AppendFormat("\"{0}\": \"{1}\"", key, dict[key]); sb.Append(key != dict.Keys.Last() ? ", " : String.Empty); } sb.Append("}"); return sb.ToString(); } 

So you can write:

 var jsonString = myDict.SerializeToJson(); 
-one
source

Source: https://habr.com/ru/post/1394703/


All Articles