Top / JUNK / Json.NET

//a.json
{
  "data": [
    {
      "id": "100_1",
      "name": "tarou",
      "dataname": "AAA",
      "value": 155
    },
    {
      "id": "100_2",
      "name": "hanako",
      "dataname": "BBB",
      "value": 50
    },
    {
      "id": "100_3",
      "name": "manami",
      "dataname": "AAA",
      "value": 120
    }
  ]
}
//b.json
{
  "definition": [
    {
      "dataname": "AAA",
      "type": "string"
    },
    {
      "dataname": "BBB",
      "type": "float"
    },
    {
      "dataname": "CCC",
      "type": "int"
    }
  ]
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args) {
            var typeDic = new Dictionary<string, Type>();
            typeDic.Add("string", typeof(string));
            typeDic.Add("float", typeof(float));
            typeDic.Add("int", typeof(int));

            var rootA = GetJson<RootData>("a.json");
            var rootB = GetJson<RootDefinition>("b.json");
            foreach (var itemA in rootA.data) {
                var itemB = rootB.definition.Find(data => data.dataname == itemA.dataname);
                if (itemB != null && itemA.value != null) {
                    var cnv = TypeDescriptor.GetConverter(itemA.value.GetType());
                    if (cnv != null) {
                        itemA.value = cnv.ConvertTo(itemA.value, typeDic[itemB.type]);
                    }
                }
            }
            var outputString = JsonConvert.SerializeObject(rootA, Formatting.Indented);
            File.WriteAllText("output.json", outputString);
            Console.WriteLine(outputString);
            Console.ReadKey();
        }

        static T GetJson<T>(string filepath) {
            string jsonstring = File.ReadAllText(filepath, Encoding.UTF8);
            return JsonConvert.DeserializeObject<T>(jsonstring);
        }

    }

    public class Data
    {
        public string id { get; set; }
        public string name { get; set; }
        public string dataname { get; set; }
        public object value { get; set; }
    }

    public class Definition
    {
        public string dataname { get; set; }
        public string type { get; set; }
    }

    public class RootData
    {
        public List<Data> data;
    }

    public class RootDefinition
    {
        public List<Definition> definition { get; set; }
    }

}
// output.json
{
  "data": [
    {
      "id": "100_1",
      "name": "tarou",
      "dataname": "AAA",
      "value": "155"
    },
    {
      "id": "100_2",
      "name": "hanako",
      "dataname": "BBB",
      "value": 50.0
    },
    {
      "id": "100_3",
      "name": "manami",
      "dataname": "AAA",
      "value": "120"
    }
  ]
}



トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   最終更新のRSS
Last-modified: 2019-08-08 (木) 10:49:35 (129d)