Reputation: 2889
I have a wcf service that must return JSON. My code looks like:
public String areaGetStreetTypes(int city_id, int language_id)
{
string json = "";
string responseList = "{\"triname\":\"IMP\",\"name\":\"IMPASSE\"}";
if (responseList.Length != 0){
string responseStatusJSON = "{\"status\":0, \"message\":\"Success !!!\"}";
json += "{\"responseList\":[" + responseList + "],";
json += "\"responseStatus\":" + responseStatusJSON + "}";
}
else{
string responseStatusJSON = "{\"status\":1, \"message\":\"Error !!!\"}";
json += responseStatusJSON;
}
return json;
}
//my interface looks like
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "areaGetStreetTypes", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
String areaGetStreetTypes(int city_id, int language_id);
Response in raw format:
{"areaGetStreetTypesResult":"{\"responseList\":[{\"triname\":\"IMP\",\"name\":\"IMPASSE\"}],\"responseStatus\":{\"status\":0, \"message\":\"Success !!!\"}}"}
I use a php script for testing. After first decoding:
stdClass Object(
[areaGetStreetTypesResult] => {"responseList":[{"triname":"IMP","name":"IMPASSE"}],"responseStatus":{"status":0, "message":"Success !!!"}}
)
Only after my second json_decode I get what I want: GOOD JSON Response
What can I change in my service to get the good JSON the first time? I want to decode only once.
Upvotes: 0
Views: 332
Reputation: 7886
You can create a class object that can be returned as shown below:
namespace Rest
{
public class JsonRes
{
public ResponseList ResponseList { get; set; }
public ResStatus ResponseStatus { get; set; }
}
public class ResponseList
{
public string triName { get; set; }
public string name { get; set; }
}
public class ResStatus
{
public string status { get; set; }
public string message { get; set; }
}
}
The WCF framework does the serialization to JSON.
If you have the json String being build dynamically from db then try to find if you can get a generic object that would be enough under all scenarios. Like having a List of object that has the column name and its value and then passing back the complete list back to the client.
Upvotes: 1
Reputation: 1464
You JSON'ing twice - one time in your method and second when you tell WCF to serialize with JSON in WebInvoke attribute.
Why not make couple more contracts and return them, instead of manually construct result string?
Upvotes: 2