我创建了一个WCF服务来返回JSON,但是,它不会以我需要的方式返回。
我的界面:
[ServiceContract]
public interface IService1
{
[OperationContract(Name="Sensors")]
[WebInvoke(
Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "test")]
List<Sensor> testdata();
}
我的服务:
public class Service1 : IService1
{
public List<Sensor> testdata()
{
return HamsData.GetSensorDetails("1");
}
}
HamsData.GetSensorDetails:
public static List<Sensor> GetSensorDetails(string id)
{
List<Sensor> al = new List<Sensor>();
DateTime now = DateTime.Now;
DateTime thishour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0);
using ( HAMSDataClassesDataContext db = new HAMSDataClassesDataContext())
{
var dbsensors = (from p in db.sensordetails where p.sensorlatestdate == thishour select new Sensor { name = p.sensor.name, value = p.sensorlatestvalue });
foreach (Sensor x in dbsensors)
{
al.Add(x);
}
return al;
}
}
传感器类:
[Serializable]
[DataContract(Name = "mysensor")]
public class Sensor
{
[DataMember]
public string name { get; set; }
[DataMember]
public decimal value { get; set; }
}
返回以下JSON:
[{"name":"EIC","value":1000.000},{"name":"GIC","value":0.000},{"name":"WIC","value":0.000},{"name":"EHC","value":0.010},{"name":"GHC","value":0.000},{"name":"WHC","value":0.000},{"name":"EDC","value":33458.560},{"name":"ENC","value":27450.040},{"name":"GRC","value":35227.100},{"name":"WRC","value":38.390},{"name":"ECR","value":1.000},{"name":"10:D8:A2:DC:01:08:00:E0:T","value":24.120},{"name":"10:94:3D:B4:01:08:00:BC:T","value":46.310},{"name":"10:31:85:70:01:08:00:4D:T","value":20.940},{"name":"10:5D:5E:B4:01:08:00:EA:T","value":7.690},{"name":"10:DD:56:B4:01:08:00:3E:T","value":17.690},{"name":"28:51:32:5D:02:00:00:0A:T","value":12.560},{"name":"26:B1:08:81:00:00:00:39:T","value":15.030},{"name":"26:B1:08:81:00:00:00:39:H","value":-29.890},{"name":"26:CD:A0:6D:00:00:00:8A:T","value":15.030},{"name":"26:CD:A0:6D:00:00:00:8A:L","value":204.600}]
但是,我希望它没有名称和值标签,如:
[{"EIC":1000.000},{"GIC":0.000},{"WIC":0.000},{"EHC":0.010},{"GHC":0.000},{"WHC":0.000},{"EDC":33458.560},{"ENC":27450.040},{"GRC":35227.100},{"WRC":38.390},{"ECR":1.000},{"10:D8:A2:DC:01:08:00:E0:T":24.120},{"10:94:3D:B4:01:08:00:BC:T":46.310},{"10:31:85:70:01:08:00:4D:T",e":20.940},{"10:5D:5E:B4:01:08:00:EA:T":7.690},{"10:DD:56:B4:01:08:00:3E:T":17.690},{"28:51:32:5D:02:00:00:0A:T"12.560},{"26:B1:08:81:00:00:00:39:T":15.030},{"26:B1:08:81:00:00:00:39:H":-29.890},{"26:CD:A0:6D:00:00:00:8A:T":15.030},{"26:CD:A0:6D:00:00:00:8A:L":204.600}]
有人能说出我在这里做错了吗?
答案 0 :(得分:1)
这不是json,这就是问题所在。 Json编码是属性/值的组合。你试图滥用它。
您确定要以这种方式对数据进行编码吗?这使得提取值变得非常困难。