Reputation: 451
I have the following JSON that I need to post to an API:
{
"arch": {
"id": “TrackingCode”
},
"nails": [{
"name": "John"
}],
"token": 'RandomCode'
}
So I define the data this way:
public class arch
{
[JsonProperty("id")]
public string id { get; set; }
}
public class nails
{
[JsonProperty("name")]
public string[] name { get; set; }
}
public class Parameter
{
[JsonProperty("arch")]
public arch arch { get; set; }
[JsonProperty("nails")]
public nails nails{ get; set; }
[JsonProperty("token")]
public string token { get; set; }
}
This is how I init the JSON before serializing it:
Parameter json = new Parameter
{
arch = new arch
{
id = TrackingId
},
nails = new nails
{
name = "John"
}
token = "randomstuff"
};
But there is a syntax/formatting error involving the "name" field that won't allow compilation. It's obviously the array structure of that element. What am I doing wrong syntax wise?
Upvotes: 0
Views: 72
Reputation: 483
In your parameter object change nails nails
to either nails[]
or IEnumerable<nail> nails
. The reason your json isn't coming out as you'd like is because nails is an object so a singular entity vs an array being multiple entities as you intended
Upvotes: 2
Reputation: 1744
I recommend you to use http://json2csharp.com/, this could be useful to generate the class objects for your JSON.
Using that tool you have:
public class Arch
{
public string id { get; set; }
}
public class Nail
{
public string name { get; set; }
}
public class Parameter
{
public Arch arch { get; set; }
public List<Nail> nails { get; set; }
public string token { get; set; }
}
As you can see name
should not be an array
. Instead nails
is (Array or list).
EDIT:
To initialize your Parameter
instance you can do this way:
Parameter json = new Parameter
{
arch = new Arch
{
id = TrackingId
},
nails = new List<Nail>
{
new Nail { name = "John" }
},
token = "randomstuff"
};
Upvotes: 0
Reputation: 1346
As far as the code you've supplied, the compile error is because you've defined name as a string array, but then you're trying to assign a string to it. Change to a string array and it will compile fine:
Parameter json = new Parameter
{
arch = new arch
{
id = "1"
},
nails = new nails
{
name = new string[]{"John"}
},
token = "randomstuff"
};
That said, this wouldn't meet your original requirement, which was that nails should be an array, not name within nails. So you need something more like:
public class arch
{
public string id { get; set; }
}
public class nails
{
public string name { get; set; }
}
public class Parameter
{
public arch arch { get; set; }
public nails[] nails { get; set; }
public string token { get; set; }
}
...
Parameter json = new Parameter
{
arch = new arch
{
id = "1"
},
nails = new nails[]
{
new nails(){name = "John"}
},
token = "randomstuff"
};
Upvotes: 1