读取JSON格式的文本并提取值

时间:2014-02-06 19:09:45

标签: json

我有JSON文件,我必须阅读它并从中提取id。我用“http://json2csharp.com/”做了课,还写了一个剧本。由于JSON格式的复杂性,我的课程有点奇怪(至少对我来说很奇怪),这就是我完全困惑的原因。可以检查脚本并告诉我如何提取id。 BTW =我通过“stackoverflow”找到了一些代码并在之前使用过它们。

脚本的总程序: 1 - 读取访问数据集,其中包含两个字段(uid,tid)-3000条记录 2 - 读取数据集中的每个uid并用url中的uid(在表中)替换(url中的标记) 3-run url和read json file if if(id == tid) - >计数器++。

json格式:

    {
      "context": "65071",
      "names": [
        "id",
        "name",
        "hash",
        "score",
        "rank"
      ],
      "values": [
        [
          "187126",
          "187126",
          "187126",
          "0.1",
          "92.7157"
        ],
        [
          "494579",
          "494579",
          "494579",
          "0.05",
          "77.6358"
        ],
        [
          "455577",
          "455577",
          "455577",
          "0.0488174",
          "76.4856"
        ].....

 ,
  "kola": 6,
  "swer": "v3-beta"
}

json class

public class Class1
    {
        public string context{ get; set; }
        public List<string> names { get; set; }
        public List<List<string>> values { get; set; }
        public int kloa { get; set; }
        public string swer { get; set; }
    }

脚本:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Net;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace test6
{
    class Program
    {
        static void Main(string[] args)
        {
            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\xa.accdb";
            conn.Open();
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = conn;
            cmd.CommandText = "Select * from xa";
            DataTable dt = new DataTable();
            //To read data from dataset
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = cmd;
            adapter.Fill(dt);
            int uid = 0;
            int tid = 0;
            int counter = 0;
            foreach (DataRow row in dt.Rows)
            {
                string url = "http://opkug/<uid>?groups=<uid>";
                var test = url.Replace("<uid>", Convert.ToString(row[uid]));
                System.Diagnostics.Process.Start(test);
                string client = (new WebClient()).DownloadString(test);
                var pi = JObject.Parse(client);
                List<List<string>> ids = values.Select(v => v[field_names.IndexOf("idz")]).ToList();
                if(ids == Convert.ToString(row[tid]))
                   {
                    counter++;
                   }
            }

            Console.ReadLine(counter);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用 Newton Soft的JSON .NET ,这是http://json.codeplex.com/提供的开源实用程序

你也可以see this tutorial用于Windows手机,但由于它是C#,它也适用于你。