-3

I have a JSON object that's a string array that looks like this. It's in a variable called "researchTerms":

[{"1":"ifn","2":7,"3":1.81818181818182},{"1":"macrophages","2":5,"3":1.2987012987013},{"1":"n =","2":5,"3":1.2987012987013},{"1":"p <","2":5,"3":1.2987012987013},{"1":"technique","2":5,"3":1.2987012987013},{"1":"cells","2":4,"3":1.03896103896104}]

How can I deserialize this in C# using Newtonsoft to an array of ResearchTerms where property "1" is Term, property "2" is Count, and property "3" is Score?:

public class ResearchTerm
{
    public string Term { get; set; }
    public int Count { get; set; }
    public long Score { get; set; }
} 
Andy
  • 1,243
  • 3
  • 22
  • 40
  • 1
    Have you tried using `[JsonProperty("1")]` etc? I haven't tried that using numerical values, but I suspect it may well just work. That's how you normally control the JSON name. – Jon Skeet Sep 21 '17 at 19:48
  • 1
    Your title results in 266000 Google hits - the first 6 on this site – Ňɏssa Pøngjǣrdenlarp Sep 21 '17 at 19:49
  • Possible duplicate of [.NET NewtonSoft JSON deserialize map to a different property name](https://stackoverflow.com/questions/15915503/net-newtonsoft-json-deserialize-map-to-a-different-property-name) – eocron Sep 21 '17 at 19:51
  • Possible duplicate of [How can I change property names when serializing with Json.net?](https://stackoverflow.com/questions/8796618/how-can-i-change-property-names-when-serializing-with-json-net) – mjwills Sep 21 '17 at 21:36

1 Answers1

3

If you are using Json.Net you can use the Attribute JsonProperty

public class ResearchTerm
{
    [JsonProperty("1")]
    public string Term { get; set; }
    [JsonProperty("2")]
    public int Count { get; set; }
    [JsonProperty("3")]
    public decimal Score { get; set; }
}
Eser
  • 12,346
  • 1
  • 22
  • 32
  • This works! I tried searching and didn't find this solution before. Thanks. – Andy Sep 21 '17 at 19:57
  • When using this, it appears to convert the Json properties back to 1, 2, 3 when serialized again to deliver to the client. Is there a way to convert the values only one way so when reading from my string in the database, it'll turn "1" to Term in my C# code and keep it that way when serialized again? I'm using this: Newtonsoft.Json.JsonConvert.DeserializeObject(personTask.Result.ResearchKeywords); – Andy Sep 21 '17 at 20:01
  • @Andy Yes there is way. But what I know from my past experience is that answering a *"new question"* in comments results in another question. Sorry, I am too lazy to jump into this loop – Eser Sep 21 '17 at 21:03
  • @Andy Have a quick squiz at https://meta.stackoverflow.com/questions/266767/what-is-the-the-best-way-to-ask-follow-up-questions – mjwills Sep 21 '17 at 21:38