0

I need to convert to dictionary JSON array of objects with key "id" and value "score" properties like the following

[{"score":0.6990418,"id":"4833909335"},
{"score":0.8079009,"id":"4833874639"},
{"score":0.8079009,"id":"4834247506"}].

Dictionary keys should have values of "id" property, and dictionary values shoud be copied from "score".

Note that it is not a deserialization, but transforming/mapping when some information not copied to target object(e.g. names of properties and potentially other properties)

I found similar question How to deserialize the json array of objects to dictionary , that was incorrectly closed as duplicate of different question about deserializing different JSON object with multiple properties. I've tried to reopen it, but without success.

Community
  • 1
  • 1
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170

2 Answers2

0

I've created extension methods to allow extract pair of properties from elements of JSON array

  public static Dictionary< string, string> JsonArrayToDictionary( string strJson, string keyName,string valueName)
        {
            var array = JArray.Parse(strJson) ;
            var dictionary = JsonArrayToDictionary(array, keyName, valueName);
            return dictionary;
        }

        public static Dictionary<string , string > JsonArrayToDictionary(this JArray array, string keyName, string valueName)
        {
            if (array != null)
            {
                var dict = array.ToDictionary(x => x[keyName].ToString(), x => x[valueName].ToString());
                return dict;
            }
            return null;
        }


 [TestClass()]
    public class JsonHelperExtensionsTests
    {
        [ TestMethod()]
        public void JsonArrayToDictionaryTest()
        {
            var jsonArray= @"[{""score "":0.6990418,"" id"": ""ID1"" },{""score "":0.8079009,"" id"": ""ID2"" }]";
           var dict= JsonHelperExtensions.JsonArrayToDictionary(jsonArray, "id" , "score");
            dict.Count.Should().Be(2);
            dict[ "ID1"].Should().Be("0.6990418" );
        }
    }
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
0

Current solution for current time:

var jsArray = JObject.Parse(response);
var arrayDictionary = JsonConvert.DeserializeObject<Dictionary<string, dynamic>[]>(jsArray.ToString());