我有一个复杂的JSON响应,我需要解析和替换数据。
这只是一天的剪辑,但需要在回复中做好所有日子。
我如何解析这个并且只是改变值。 我需要修改并发送回主机。
{
"schedulePeriods":` [
{
"day": "Monday",
"periodType": "WakeOcc1",
"startTime": 26,
"isCancelled": false,
"heatSetpoint": 70.0,
"coolSetpoint": 75.0,
"fanMode": "Auto"
},
{
"day": "Monday",
"periodType": "LeaveUnocc1",
"startTime": 32,
"isCancelled": false,
"heatSetpoint": 65.0,
"coolSetpoint": 75.0,
"fanMode": "Auto"
},
{
"day": "Monday",
"periodType": "ReturnOcc2",
"startTime": 66,
"isCancelled": false,
"heatSetpoint": 72.0,
"coolSetpoint": 75.0,
"fanMode": "Auto"
},
{
"day": "Monday",
"periodType": "SleepUnocc2",
"startTime": 0,
"isCancelled": false,
"heatSetpoint": 65.0,
"coolSetpoint": 75.0,
"fanMode": "Auto"
},
{
"day": "Tuesday",
"periodType": "WakeOcc1",
"startTime": 26,
"isCancelled": false,
"heatSetpoint": 70.0,
"coolSetpoint": 75.0,
"fanMode": "Auto"
},
所以我现在拥有的是:`
class Day
{
public string day { get; set; }
public string periodType { get; set; }
public int startTime { get; set; }
public double heatSetpoint { get; set; }
public double coolSetpoint { get; set; }
public override string ToString()
{
return string.Format("{0}\n{1}\n{2}\n{3}\n{4}", day, periodType, startTime, heatSetpoint, coolSetpoint);
}
}
static void Main(string[] args)
{
String JSONstring = File.ReadAllText("json.json");
JObject o = JObject.Parse(JSONstring);
string day = (string)o.SelectToken("schedulePeriods[0].day");
string periodType = (string)o.SelectToken("schedulePeriods[0].periodType");
int startTime = (int)o.SelectToken("schedulePeriods[0].startTime");
double heatSetpoint = (double)o.SelectToken("schedulePeriods[0].heatSetpoint");
double coolSetpoint = (double)o.SelectToken("schedulePeriods[0].coolSetpoint");
Console.WriteLine("{0}\n{1}\n{2}\n{3}\n{4}",day,periodType,startTime,heatSetpoint,coolSetpoint);
Console.WriteLine("Change Value to:");
string answer = Console.ReadLine();
day = answer;
Console.WriteLine("new value {0}", day);
string data = JsonConvert.SerializeObject(JSONstring,Formatting.Indented);
File.WriteAllText("newfile.json", data);
Console.ReadLine();
}
我可以从第一个大括号中获取数据,但没有更多。 我需要从每个阵列中获取。 我还想修改一个给定的条目,然后用适当的json格式保存编辑的文件(这根本不起作用)`
解决。 感谢您的反馈
答案 0 :(得分:2)
在您的应用程序中创建以下类
public class RootObject
{
public List<SchedulePeriod> schedulePeriods { get; set; }
}
public class SchedulePeriod
{
public string day { get; set; }
public string periodType { get; set; }
public int startTime { get; set; }
public bool isCancelled { get; set; }
public double heatSetpoint { get; set; }
public double coolSetpoint { get; set; }
public string fanMode { get; set; }
}
然后使用Newtonsoft.Json反序列化你的json,如
public static T DeserializeObject<T>(string jsonObj)
{
return JsonConvert.DeserializeObject<T>(jsonObj,
new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented });
}
并称之为
RootObject obj = DeserializeObject<RootObject>(your_json);
然后访问您的日程安排。
希望它有所帮助。