Jack
Jack

Reputation: 2660

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.

Upvotes: 0

Views: 434

Answers (2)

Usman Tiono
Usman Tiono

Reputation: 224

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

Upvotes: 0

Jakub Konecki
Jakub Konecki

Reputation: 46008

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

Upvotes: 2

Related Questions