我目前正在与第三方API集成,他们接受类似于以下格式的json字符串:
{
"test-specialism": null,
"salaryCollection": [
{
"id":
{
"jobtypeid": 1
},
"maxsalary": 564,
"minsalary": 123,
"salarycurrency": "GBP",
"salarytype": "A"
},
{
"id":
{
"jobtypeid": 2
},
"maxsalary": null,
"minsalary": null,
"salarycurrency": "GBP",
"salarytype": null
},
}],
}
这是我的目标:
public class Salary {
public double Minimum { get; set; }
public double Maximum { get; set; }
public PaymentFrequency Frequency { get; set; }
public double Step { get; set; }
public int JobTypeId { get; set; }
public SalarySetting() { }
}
public class Alert {
public string Specialism {get;set;}
public Salary Permanent { get; set; }
public Salary Temporary { get; set; }
public Salary Contract { get; set; }
}
正如您所看到的,对象结构与JSON结构非常不一致。将对象转换为指定的json字符串的理想方法是什么?我尝试使用JSONProperty映射属性,在这种情况下似乎不能正常工作。
答案 0 :(得分:2)
答案 1 :(得分:0)
您可以使用System.Web.Script.Serialization.JavaScriptSerializer。示例:
public class Product{
public string Name { get; set; }
public string ID { get; set; }
}
我将在列表中添加一些实例:
Product p1 = new Product {Name="Product1",ID="1"};
Product p2 = new Product {Name="Product2",ID="2"};
List<Product> pList = new List<Product>() {p1,p2};
然后我要序列化它:
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = serializer.Serialize(pList);