XamarinDevil
XamarinDevil

Reputation: 891

HTTP POST - Json

I am trying to post my json values in the nested format as below but in my code, my data is submitted singly which is a constraint in the database. I select a number of doctors from my phone app and when i click save, the httpRequest much submit all the doctors selected singly as in the nested format. How can i submit the data in the nested format?

my code

Hospitals = {
  hospital : "New York hospital",
  doctor: {
     details: {  
      id: "",
      ward: ""          
     }
  }
}

//this is how i post to the server 
 saveDoctorsForHospitals(){   
    Object.keys(this.Doctors).filter(key => this.Doctors[key].find)
       .forEach(key => {
           this.Hospitals.Doctors.details.id = this.Docotrs[key].id
           this.Hospitals.Doctors.details.ward = this.Doctors[key].ward

    this.httpService.submitAll(this.Hospitals)
        .subscribe(data => {
           console.log(data);   
        })

this is how my data is submitted now

  object 1         
    "hospital" : "McJames",
    "Doctor" : {
       "1" : {
          "id": 1269,
          "ward": "Demarco",                    
       }        
  Object 2
     "hospital" : "McJames",
     "Doctor" : {
        "2" : {
           "id": 1269,
           "ward": "Demarco",     
        }


//but i want to be this 

    {
      "hospital" : "McJames",
      "Doctor" : {
         "1" : {
           "id": 1269,
            "ward": "Demarco",    
         },

         "2" : {
            "id": 1275,
            "ward": "Eden",
          }
        }
      }

updated - wrapping in array

Hospitals = {
  hospital : "New York hospital",
  doctor: [{
     details: {  
      id: "",
      ward: ""          
     }
  }]
}

Upvotes: 0

Views: 80

Answers (1)

DeborahK
DeborahK

Reputation: 60596

The code here:

Hospitals = {
  hospital : "New York hospital",
  doctor: {
     details: {  
      id: "",
      ward: ""          
     }
  }
}

Defines what you are posting. This data structure is saying that you have one hospital property with a string value and one doctor property that is an object. If you want multiple doctors, you'll need to change this structure such that the doctors are defined as an array.

You could use interfaces such as this:

interface Hospital {
    hospital: string;
    doctors: Doctors[]
}
interface Doctors {
    id: number,
    ward: string
}

class Test {
    hospitals: Hospital[] = [];
    constructor() {
        this.hospitals.push({
            hospital: "New York Hospital",
            doctors: [{
                id: 1269,
                ward: "test"
            }]
        })
    }
    data() {
        return JSON.stringify(this.hospitals);
    }
}

Upvotes: 1

Related Questions