0

This is my object and i'm getting list of this object:

public class MeetingTypeModel
{
    public string MeetingTypeId { get; set; }
    public string MeetingTypeName { get; set; }
}

List<MeetingTypeModel> MeetingTypeList

I want to convert it into format:

({ "1": "Bangladesh", "2": "Belgium"})
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Raj SOni
  • 21
  • 4
  • 1
    Convert your list into a Dictionary pre serializing. – StuartLC May 29 '18 at 05:09
  • just asking all of you guys can he achieve this by overriding the String.Join() method? – Lucifer May 29 '18 at 05:16
  • @Lucifer what do you mean, by overriding `String.Join()` method? – Yurii N. May 29 '18 at 05:18
  • we can have a list in a CSV format by using String.Join() what if user uses that logic and creates his own method to achieve `({ "1": "Bangladesh", "2": "Belgium"})` .I am just asking can we or can we not? c# – Lucifer May 29 '18 at 05:20
  • 2
    @Lucifer you can't override `string.Join`, it is a static method on a `Type`. you could create a different type `StringExtensions` and an Extension method called `public static string Join(this string, bool myMethodSignatureIsDifferent, params string[] args)` as some sort of overload concept to `string.Join` more or less. but that would still not be static method on `string`. and it would only serve to confuse people. – Brett Caswell May 29 '18 at 05:26
  • Do you need to effectively generate a JSON representation of your list or is it just a coincidence that you need the output to be formatted this way ? – Spotted May 29 '18 at 05:41

4 Answers4

4

The way you shouldn't create a json Dictionary

var temp = MeetingTypeList.Select(x => $"\"{x.MeetingTypeId}\" : \"{x.MeetingTypeName}\"");
var json = $"{{ {string.Join(", ", temp)} }}";

They way you should create a json Dictionary

var dict = MeetingTypeList.ToDictionary(x => x.MeetingTypeId, x => x.MeetingTypeName); 
string json = JsonConvert.SerializeObject(dict, Formatting.Indented);

Update from Brett Caswells comments

Some considerations to this.

  • We cannot guarantee Distinction with MeetingTypeId MeetingTypeName pairing (it doesn't likely though).
  • Whether "(" is prepended and ")" appended to the result of this serialization.

If you need the extra parenthesises

json = $"({json})";
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
1

Simply add reference to Newtonoft.Json and add using Newtonsoft.Json;

var MeetingTypeList = new List<MeetingTypeModel>();
// add data to list
string json = JsonConvert.SerializeObject(MeetingTypeList);
Awais Mahmood
  • 1,308
  • 4
  • 21
  • 51
  • you are also going to have to decorate the properties with `[JsonProperty("1")]` and `[JsonProperty("2")]`... – Zohar Peled May 29 '18 at 05:29
  • this is probably incorrect. the result output OP put forward uses value of `MeetingTypeId ` property as a field – Brett Caswell May 29 '18 at 05:29
  • to clarify, wouldn't the result of this serialization be: `[{ "MeetingTypeId" : "1", "MeetingTypeName" : "Bangladesh" }, {"MeetingTypeId" : "2", "MeetingTypeName" : "Belgium" }]` – Brett Caswell May 29 '18 at 06:02
0

If you would like to avoid using external libraries, you could do it item by item like the following:

    StringBuilder SB = new StringBuilder();
    SB.Append("({");
    for(int i=0; i<MeetingTypeList.Count; i++) {
        MeetingTypeModel mtm = MeetingTypeList[i];

        SB.AppendFormat("\"{0}\":"\"{1}\", mtm.MeetingTypeId, mtm.MeetingTypeName);
        if {i<MeetingTypeList.Count -1) {
          SB.Append(",");
        }
    }
    SB.Append("})");
PepitoSh
  • 1,774
  • 14
  • 13
0

You can iterate through list and by using StringBuilder, you can generate expected output

public string GetString(List<MeetingTypeModel> MeetingTypeList)
{
StringBuilder sb = new StringBuilder();
sb.Append("({");
int i = 1;
foreach(MeetingTypeModel item in MeetingTypeList){

    sb.AppendFormat("\"{0}\" : \"{1}\"" , item.MeetingTypeId, item.MeetingTypeName);
    //To not append last comma
    if(i != MeetingTypeList.Count)
        sb.Append(",");
    i++;
}
sb.Append("})");
return sb.ToString();
}

POC: DotNetFiddler

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • Your code will have an extra comma – SSS May 29 '18 at 05:26
  • @SSS I updated my answer, why downvote, I can work on your suggestions – Prasad Telkikar May 29 '18 at 05:39
  • your answer is correct, and doesn't warrant a downvote; but, I wouldn't upvote this, since I consider it to be low quality by virtue of using `StringBuilder`. `StringBuilder` does have it's role, but the better answers here are going to involve serialization. – Brett Caswell May 29 '18 at 06:23
  • I didn't downvote, someone else did – SSS May 29 '18 at 06:24
  • @BrettCaswell, I agreed that serialization would be elegant approach over function which I wrote. I used `StringBuilder` as it is mutable and having advantages over `string` – Prasad Telkikar May 29 '18 at 06:30