我正在为 excel 开发一个自定义插件,我希望它从远程 Web 服务中获取项目列表。JSON 正在从 web servive 返回到 excel,但我无法将 JSON 转换为 C# 中的对象。
这是插件代码:
using Microsoft.Office.Tools.Ribbon;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Web;
namespace TestAddIn
{
class Project
{
static string currentProject;
static List<Project> validProjects;
public int id { get; set; }
public string name { get; set; }
public int svar_reserved_space { get; set; }
// Set the current project we're working on
internal static void setCurrentProject(string path)
{
Match match = Regex.Match(path, @"^[A-Za-z]:\\(\w+)");
Project.currentProject = match.Groups[1].Value;
foreach (Project validProject in validProjects)
{
RibbonDropDownItem dropDown = Globals.Ribbons.Ribbon1.Factory.CreateRibbonDropDownItem();
dropDown.Label = validProject.name;
if (validProject.name.Equals(Project.currentProject))
{
Globals.Ribbons.Ribbon1.projectComboBox.Items.Add(dropDown);
}
}
}
// Connect to a web service and get a list of valid projects
internal static void getValidProjects()
{
string url = "http://192.168.118.128/projects/json";
WebRequest webRequest;
webRequest = WebRequest.Create(url);
Stream objStream;
objStream = webRequest.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string sLine = objReader.ReadLine();
Debug.WriteLine("begin: " + sLine);
validProjects = JsonConvert.DeserializeObject<List<Project>>(sLine);
Debug.WriteLine("end");
}
}
}
使用此 json 时:
[{"Project":{"id":1,"name":"test1","svar_reserved_space":2}},{"Project":{"id":2,"name":"test2","svar_reserved_space":0}}]
我在 validProjects 中有两个 Project 对象,但 id 和 svar_reserver_space 为 0,名称为 null。思想?