Reputation: 157
I Create a simple WCF service and he works fine. The configuration are below The interface have this configuration
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "checkSymbolExistJson/{pSymbol}")]
string checkSymbolExistJson(string pSymbol);
The implementation is this
public string checkSymbolExistJson(string pSymbol)
{
Person p = new Person();
p.name = pSymbol;
p.age = 15;
string json = JsonConvert.SerializeObject(p);
return json;
}
if I enter URL in browser "http://localhost/MetaTraderWcf/rzManageQuotes.svc/checkSymbolExistJson/testename" in brower I Get this result in Browser
"{\"name\":\"testename\",\"age\":15}"
After I make a win 32 application to get http result of this WCF service. I use this code to read a HTML page
public string readUrl(string pUrl)
{
WebClient client = new WebClient { Encoding = System.Text.Encoding.UTF8 };
return client.DownloadString(pUrl);
}
I use this code to read a JSON dinamic TAG
private void button2_Click(object sender, EventArgs e)
{
string tmpToken = readUrl(url.Text);
// string tmpToken = "{\"name\":\"testename\",\"age\":15}";
JToken token = JObject.Parse(tmpToken);
string page = (string)token.SelectToken("name");
jSONResult.Text = page;
}
if I Runing code above with fixed code below
string tmpToken = "{\"name\":\"testename\",\"age\":15}";
The result is correct and I get result as "testename".
But when I Debug the read a Html page I receive tha value of tmpToken with this string
"\"{\\"name\\":\\"testename\\",\\"age\\":15}\""
And I get a error when I read dinamic value of name
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Additional information: Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 37.
If I change interface to return a XML page like this code
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "checkSymbolExistJson/{pSymbol}")]
string checkSymbolExistJson(string pSymbol);
I get the follow result in browser
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">{"name":"testename","age":15}</string>
And I get Read JSON value of name correct after remove tag from XML result.
The Question is There is some way of read a string in pure JSON format in c# like a read in a Browser format like this
{"name":"testename","age":15}
and not like this format
"\"{\\"name\\":\\"testename\\",\\"age\\":15}\""
Upvotes: 1
Views: 2081
Reputation: 2764
there is a simple solution for that. just return stream
except string
.
public stream checkSymbolExistJson(string pSymbol)
{
Person p = new Person();
p.name = pSymbol;
p.age = 15;
string json = JsonConvert.SerializeObject(p);
return new MemoryStream(Encoding.UTF8.GetBytes(json));
}
or i suggest use web API instead WCF.
Upvotes: 3