Question

I have following code snippet in which I am serializing an object into JSON. The code is working fine, but I want to remove Key and Value keywords from the JSON string.

Current output:

{
   "Description":"test",
   "RoomTypes":[
      {
         "Key":"A",
         "Value":{
            "Name":"Delux"
         }
      },
      {
         "Key":"B",
         "Value":{
            "Name":"Non delux"
         }
      }
   ],
   "Url":"http:\/\/test.com"
}

Desired output:

{
   "Description":"test",
   "RoomTypes":[
      {
         "A":{
            "Name":"Delux"
         }
      },
      {
         "B":{
            "Name":"Non delux"
         }
      }
   ],
   "Url":"http:\/\/test.com"
}

My test code:

namespace ConsoleApplication1
{
    [DataContract]
    public class Room
    {
        [DataMember]
        public string Url { get; set; }
        [DataMember]
        public string Description { get; set; }
        [DataMember]
        public Dictionary<string, RoomTypes> RoomTypes { get; set; }
    }

    [DataContract]
    public class RoomTypes
    {
        [DataMember]
        public string Name { get; set; }
    }

    public class Test
    {
        static void Main(string[] args)
        {
            Room room = new Room { Url = "http://test.com", Description="test" };
            RoomTypes roomType1 = new RoomTypes() { Name = "Delux" };
            RoomTypes roomType2 = new RoomTypes() { Name = "Non delux" };
            room.RoomTypes = new Dictionary<string, RoomTypes>();
            room.RoomTypes["A"] = roomType1;
            room.RoomTypes["B"] = roomType2;

            DataContractJsonSerializer dataContractSer = 
                   new DataContractJsonSerializer(typeof(Room));
            StringBuilder sb = new StringBuilder();
            MemoryStream ms = new MemoryStream();
            dataContractSer.WriteObject(ms, room);
            var result = Encoding.UTF8.GetString(ms.ToArray());
            Console.WriteLine(result);
        }
    }
}

Is there a way to do this?

Was it helpful?

Solution

It's not fun, but try this:

[Test]
public void Json()
{
         var input = @"{
   ""Description"":""test"",
   ""RoomTypes"":[
      {
         ""Key"":""A"",
         ""Value"":{
            ""Name"":""Delux""
         }
      },
      {
         ""Key"":""B"",
         ""Value"":{
            ""Name"":""Non delux""
         }
      }
   ],
   ""Url"":""http:\/\/test.com""
}";

    var temp = JsonConvert.DeserializeObject<Temp>(input);
    var transform = new Transform
        {
            Description = temp.Description,
            Url = temp.Url,
            RoomTypes = new List<IDictionary<string, Temp.NameObj>>()
        };

    foreach (var group in temp.RoomTypes)
    {
        var dic = new Dictionary<string, Temp.NameObj> {{@group.Key, @group.Value}};
        transform.RoomTypes.Add(dic);
    }

    Console.WriteLine(JsonConvert.SerializeObject(transform));
}

public class Transform
{
    public string Description { get; set; }
    public IList<IDictionary<string, Temp.NameObj>> RoomTypes { get; set; }
    public string Url { get; set; }
}


public class Temp
{
    public string Description { get; set; }
    public IList<GroupObj> RoomTypes { get; set; }
    public string Url { get; set; }

    public class GroupObj
    {
        public string Key { get; set; }
        public NameObj Value { get; set; }
    }

    public class NameObj
    {
        public string Name { get; set; }
    }
}    

The idea is to use Json.Net's dictionary serialization to achieve the structure you want.

OTHER TIPS

If you are using the .NET Framework v4.5 or later you can set the DataContractJsonSerializerSettings.UseSimpleDictionaryFormat setting to true to get closer to the format you want:

var settings = new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;

var dataContractSer = new DataContractJsonSerializer(typeof(Room), settings);

Using the test code from the question with the above modification produces the following output, which may be what you are looking for (although it differs from the desired output as stated in the question):

{
  "Description": "test",
  "RoomTypes": {
    "A": {
      "Name": "Delux"
    },
    "B": {
      "Name": "Non delux"
    }
  },
  "Url": "http://test.com"
}

Its because you are using dictionary for storing the value. You have to write a custom implementation and overide serialization/deserialization methods

Look here for more details

I realize that you don't want to use Json.NET, but seriously, this is the library built-to-purpose for handling JSON serialization. Your requirement is fully met by Json.NET and all you need to do is write it as a single line of code...

(From the documentation:)

Dictionary<string, int> points = new Dictionary<string, int>
{
    { "James", 9001 },
    { "Jo", 3474 },
    { "Jess", 11926 }
};

string json = JsonConvert.SerializeObject(points, Formatting.Indented);

Console.WriteLine(json);
// {
//   "James": 9001,
//   "Jo": 3474,
//   "Jess": 11926
// }

http://www.newtonsoft.com/json/help/html/serializedictionary.htm

simply you can modify your string with string replace function try This

>   public string updatejson (string jsonorg)
>     {
>         string updatedjson = "";
>         updatedjson = jsonorg.Replace("\"Key\":", "");
>         updatedjson = updatedjson.Replace("\"Value\":", "");
>         updatedjson = updatedjson.Replace("\",", "\":");
>         updatedjson = updatedjson.Replace("},{", ",");
>         updatedjson = updatedjson.TrimStart('[');
>         updatedjson = updatedjson.TrimEnd(']');
> 
>         return updatedjson;
>     }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top