NSJSONSerialization with C# Rest Service - c#

So I'm a complete noob with C# and web stuff and trying to figure something out. There is some code that says this:
[WebInvoke(UriTemplate = "People", Method = "GET", ResponseFormat = WebMessageFormat.Json)]
public string GetPeople() {
Person results = DataAccess.ParsePeople();
System.WebScrip.Serialization.JavaScriptSerializer oSerializer = oSerializer.MaxJsonLength = int.MaxValue;
string sJSON = oSerializer.Serialize(results);
return sJSON;
}
When I type in the url for this method, my response looks like:
"{\"AddressesCollection\":[{\"Street\":\"1234 Temp Dr\",\"Zip\":94011},{\"Street\":\"56789 Nothing Dr\",\"Zip\":2222},\"ErrorMessage\":\"SUCCESS\"}"
I was trying to follow this tutorial on the iPad side: http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Looking at the website they used as an example, the JSON output looks like:
{"paging":{"page":1,"total":4440,"page_size":20,"pages":222},"loans":[{"id":447290,"name":"Rosa","description":{"languages":["es","en"]},"status":"fundraising","funded_amount":0,"basket_amount":0,"image":{"id":1134583,"template_id":1},"activity":"Animal Sales","sector":"Agriculture","use":"to buy barnyard fowl and feed.","location":{"country_code":"PE","country":"Peru","town":"M\u00f3rrope - Lambayeque","geo":{"level":"country","pairs":"-10 -76","type":"point"}},"partner_id":143,"posted_date":"2012-07-13T19:00:05Z","planned_expiration_date":"2012-08-12T19:00:05Z","loan_amount":400,"borrower_count":1},{"id":447292,"na
On the iPad, when I do:
NSDictionary *fields = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
or
NSArray *fields = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
both are empty. Is it the output of the C# that is not proper JSON? Thanks.

Your JSON string is missing a closing ] somewhere.
Assuming the string you posted is exactly what was returned by the server, you will also probably need to remove the backslashes in order to make it valid JSON.
NSString *responseString = [[[NSString alloc] initWithData:response] stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSDictionary *fields = [NSJSONSerialization JSONObjectWithData:responseString options:kNilOptions error:&error];

Related

Insert in DB a JSON object from a URL

I'm new to the REST API world. I explain my need: at a specific URL I have a raw JSON text, I would like this text to be acquired by my application and inserted later in the DB as a model I created previously through EF. C# NET-CORE 2.2.
if I wasn't clear enough, don't hesitate to ask me for more details.
Thanks in advance!
Edit:
I'm sorry if it' was unclear, I will provide more detail:
Actually, i have a JSON string downloaded from an url. I did it with the following code:
var client = new WebClient();
var jsonFull = client.DownloadString(string.Format("https://url"));
It's working fine. Now, I need to take from this string only a little part of the JSON, so i did:
using var jsonDoc = JsonDocument.Parse(jsonFull);
var jsonParsed = jsonDoc.RootElement;
var myCV = jsonParsed.GetProperty("cv");
CVE is an object of this JSON, and I succesfully take it.
Inside this object, there is another one called CV_data, so I extract this:
var myCVLE = myCV.GetProperty("CV_data_meta");
The result is a var with inside
ValueKind = Object : "{
"ID": "CV-2019",
"ASS": "cv#ms.org"
}"
Now, I have a class like that
public class CV_data_meta
{
[JsonPropertyName ("ID")]
public string ID { get; set; }
[JsonPropertyName("ASS")]
public string ASS { get; set; }
}
The question is: how i can put the value in the var myCVLE in the class CV_data_meta?
I tried with
var myCVClass = JsonSerializer.Deserialize<CV_data_meta>(myCVLE);
But I get an error.
Note: I can't deserialize all the string JSON into an object, because there are a lot of information that I don't need.
Thanks in advance all!
As I understand from your question, it follows:
You first need to create the JSON object mapping (class) that the API URL will return.
Then consume the API url like this:
var client = new WebClient();
var reply =
client.DownloadString(
string.Format("https://www.yourapi.com/yourpath?yourkey={0}", yourkey));
receive and map object with mapped class
var yourvar = JsonConvert.DeserializeObject<yourclass>(reply);
Now you have the API return mapped to a class in your application, you can do whatever you want with it, including saving to a database.

Unable to do C# Restful authentication (API Key/Secrete is correct)

I would like to convert the authenticated REST request of JS (below) to C# code - using RestSharp lib (as shown) I seems not building the signature correctly. Please help..
Rest response keep response with "Invalid API Key" (which the key/secret are confirmed correct)
// sample code using the crypto lib to build the RESTFUL request
const crypto = require('crypto')
const request = require('request')
const apiKey = 'test'
const apiSecret = 'test'
const url = 'version/auth/abc'
const nonce = Date.now().toString()
const body = {}
const rBody = JSON.stringify(body)
// try build the RESTFUL signature here using crypto lib and use sha384
// Not quite sure what's the update does here though.
let signature = `/api/${url}${nonce}${rBody}`
signature = crypto
.createHmac('sha384', apiSecret)
**.update(signature)**
.digest('hex')
// all code above is fine. And this is the sample code only, and trying to do something same in C# and have tried the following. I believe is the way create the "signature" issue.
I have written the C# code below, but not working, please kindly point out, I guess is the signature building is incorrect somehow.
private uint64 _nonce = UnixTimestamp.CurrentTimeInMillis;
public uint64 MyNonce()
{
return ++_nonce;
}
private string MySignature(string jsonData)
{
byte[] data = Encoding.UTF8.GetBytes(jsonData);
_hasher = _hasher ?? new HMACSHA384(Encoding.UTF8.GetBytes(PrivateApiSecret));
byte[] hash = _hasher.ComputeHash(data);
return GetHexString(hash);
}
// try to build the request below in a method.
// only show method body below:
// using the RestSharp client to build Restful req.
var client = new RestClient(new Uri("the API address goes here"));
var request = new RestRequest(string.Format("auth/abc"), Method.POST);
// try do something similar and serialize to json in order to build the signature.
Dictionary emptyBody= new Dictionary();
string url = "version/auth/abc";
string rawBody = JsonConvert.SerializeObject(emptyBody);
string sign = $"/api/{url}{MyNonce()}{rawBody}";
string sign64= Convert.ToBase64String(Encoding.UTF8.GetBytes(sign));
string signature = MySignature(sign64);
// add the key and signature above to the header of reqest.
request.AddHeader("nonce", GetNonce());
request.AddHeader("apikey", PrivateApiKey);
request.AddHeader("signature", signature);
// well, you don't need me to explain this line don't you?
var response = request.Execute(....);
Hope this is clear enough. Thanks in advance.

send the unicode value from Android to C# Webservice

I'm trying to send the Unicode value to WCF web service from Android app but I keep getting the string value as ????? in WCF web service. Below are the android code and C# code for web service.
GTPostData gtPostData = new GTPostData(); //DTO Object
Gson gson = new Gson();
String post = "イメージお願いし";
gtPostData.setPortalId(portalId);
gtPostData.setPost(post);
gtPostData.setProjectId(data.getProjectId());
gtPostData.setQuestionId(data.getQuestionId());
gtPostData.setUserId(panelistId);
GTPostDataRequest request = new GTPostDataRequest();
request.setGtPostData(gtPostData);//creating the request object
JSONObject jsonObject = new JSONObject(gson.toJson(request));
String webServiceUrl= ResourcePicker.getServiceURL(session.getPortal(),session.getPortalId(),true);
String addGtPostMethod = ResourcePicker.getString(portal, "add_gt_post");
AsyncPostRequest asyncRequest = new AsyncPostRequest();
asyncRequest.setServiceMethod(addGtPostMethod);
asyncRequest.setServiceUrl(webServiceUrl);
asyncRequest.setPostObject(jsonObject);//set object for post call
SendGtPostAsyncService asyncService = new SendGtPostAsyncService(asyncRequest, context, session, db, data.getPostId());
asyncService.execute();//call the async task
WCF web service call (C#)
public bool AddGTPost(GTPostData GtPostData)
{
bool isAdded = false;
try
{
sci.Debug(frendlyName, screenName, "", "Enter AddGTPost ->> " + GtPostData);//These are trace methods which will print the results in txt file.
sci.Debug(frendlyName, screenName, "", "Enter AddGTPost - Unicode Post ->> " + GtPostData.post);//These are trace methods which will print the results in txt file. Here I'm getting results as "??????"
So please some one help me what is my mistake here?
For your webservice I hope you are not missing UTF-16 format
also in the configuration you are using :
Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);
GlobalizationSection configSection = (GlobalizationSection)config.GetSection("system.web/globalization");
configSection.RequestEncoding = Encoding.Unicode;
configSection.ResponseEncoding = Encoding.Unicode;

C# WCF JSON Return String

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}\""
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.

How to create simpliest PHP Get API with UTF-8 support?

How to create simpliest *(less lines of code, less strange words) PHP Get API *(so any programm made in .Net C# could call url like http://localhost/api.php?astring=your_utf-8_string&bstring=your_utf-8_string ) with UTF-8 support?
What I need Is PHP API with one function - concatinate 2 strings so that a simple .net client like this would be able to use it:
public string setStream(string astring, string bstring)
{
string newAstring =Uri.EscapeDataString(astring);
string newBstring = Uri.EscapeDataString(bstring);
WebClient client = new WebClient();
var result = client.DownloadString(("http://localhost/api.php?" + string.Format("astring={0}&bstring={1}", newAstring, newBstring)).ToString());
return result;
}
public string SetStream(string astring, string bstring)
{
using (var client = new WebClient())
{
var values = new NameValueCollection() {
"astring", astring,
"bstring", bstring
};
var result = client.UploadValues(
"http://localhost/api.php",
"GET",
values
);
return Encoding.Default.GetString(result);
}
}
Dunno if I'm missing something, but:
<?php
function concatinateStrigs($a, $b){
return $a . $b;
}
echo concatinateStrigs($_GET['astring'], $_GET['bstring']);
?>

Categories

Resources