4

I am facing the problem that using JSON to pass an object to C# and C# pass a string back to Java and then java deserialize it to a Map BTW, the .net version is 3.5

Here is the problem

the java map JSON string is 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 find a way to do this:

  1. for java Map JSON format, C# could deseralize it
  2. for C#, find a way to seralize it to a java understandable format

Thanks

1
  • 2
    Which serializer are you using? JavaScriptSerializer or DataContractJsonSerializer? (or a third-party serializer) Commented Feb 3, 2012 at 22:16

2 Answers 2

5

Try to use JavaScriptSerializer instead of DataContractJsonSerializer:

var dict = new Dictionary<string, string>
{
    { "key1", "value1" },
    { "key2", "value2" }
};
var jss = new JavaScriptSerializer();
string json = jss.Serialize(dict); // {"key1":"value1","key2":"value2"}
Sign up to request clarification or add additional context in comments.

Comments

-1

I wrote an extension method for Dictionary to serialize it to 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();

1 Comment

What if dict[key] contains "? Or worse something like haha","key666":"value666

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.