简体   繁体   中英

what's the best way to map object to random format json string

I am currently integrating with a third party API, they are accepting json string similar to the following format :

{    
"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
           },
    }],

}

And here is my object:

   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; }
}

As you can see the object structure is very inconsistent with the JSON strucuture. What would be an ideal way to convert the object to that specified json string? I've tries JSONProperty to map the property, that doesn't seem to work well in this case.

  1. Create classes that describe your json
  2. Use AutoMapper to map from your classes to json-related classes.

You can use System.Web.Script.Serialization.JavaScriptSerializer . Example :

public class Product{
    public string Name { get; set; }
    public string ID { get; set; }   
}

And I will adding some instances to Lists :

Product p1 = new Product {Name="Product1",ID="1"};
Product p2 = new Product {Name="Product2",ID="2"};
List<Product> pList = new List<Product>() {p1,p2};

Then I'm going to serialize it :

System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = serializer.Serialize(pList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM