c# - Using object in API response -
i'm building api responds requests. 1 field object , needs repeated data many times query returns.
can give me example of how use object in response c#? class need create?
thanks in advance.
add:
so far have structure like:
public class root { public int model { get; set; } public string lang { get; set; } public part[] parts { get; set; } } public class part { public int id { get; set; } public string name { get; set; } public type part_types { get; set; } } public class type { public string url { get; set; } public string desc { get; set; } }
and response coming
{ "model" : 4 , "lang" : "en_us", "parts" : [ { "id" : 1545, "name" : "part 1", "part_types" : { "url" : "part.com/type1", "desc" : "has 6 bits" } } ] }
but need like
{ "model" : 4 , "lang" : "en_us", "parts" : [ { "id" : 1545, "name" : "part 1", "part_types" : { "type 1" : { "url" : "part.com/type1", "desc" : "has 6 bits" }, "type 2" : { "url" : "part.com/type2", "desc" : "has 7 bits." } } } ] }
the part_type field object , made class called type. need have 1 or many type , specify name of type eg "type 1" have 2 more fields under url , desc. can see above has 2 type, type 1 , type 2.
can me going wrong?
so, if understand correctly, want "part_types" able have many parts? in current code, part_types object can have one.
you need 2 things: 1. data type collection, , 2. serializer writes data type way want. so, example, can use dictionary (system.collections.generic.dictionary).
public dictionary<string,type> part_types { get; set; }
so, assuming have created objects type1 , type2, write:
mypart.part_types = new dictionary<string,type>(); mypart.part_types.add("type 1", type1); mypart.part_types.add("type 2", type2);
now happens depends on serializer. typically use json.net, works , free. set objects yours using dictionary, , get:
{ "model": 4, "lang": "en_us", "parts": [ { "id": 1545, "name": "part 1", "part_types": { "type 1": { "url": "part.com/type1", "desc": "has 6 bits" }, "type 2": { "url": "part.com/type1", "desc": "has 6 bits" } } } ] }
i think that's you're looking for... however, using datacontractjsonserializer (system.runtime.serialization.json.datacontractjsonserializer), this:
{ "lang": "en_us", "model": 4, "parts": [ { "id": 1545, "name": "part 1", "part_types": [ { "key" : "type 1", "value": {"desc":"has 6 bits","url":"part.com\/type1"} }, { "key" : "type 2", "value": {"desc":"has 6 bits","url":"part.com\/type1"} } ] } ] }
i'm not sure how datacontractjsonserializer handles other collections (e.g. lists, keyvaluepairs, etc.) if you're using it, may need experiment.
Comments
Post a Comment