I am trying to read json into my C# application from a url. When I run the application I keep getting a error:
"Additional Text encountered after finished reading JSON content: {. Path ",line 2, position 667".
This is from this URL
I checked the page and the view source and can't seem to find the problem. How do I fix this?
The JSON is derived from a php array that is json encoded and echoed:
$args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'Alcopops' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo json_encode($product);
endwhile;
wp_reset_query();
That page doesn't contain valid json. Take a look at this:
"product_type":"simple"}{"id":246,"post":
there's no comma between } and {
Edit:
The problem is with your php, rather than the c#.
Try this:
$args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'Alcopops' );
$loop = new WP_Query( $args );
echo json_encode($loop->get_posts());
wp_reset_query();
use WebClient :
var json = new WebClient().DownloadString("http://cbbnideas.com/brydens-website/products/?category=Alcopops");
Related
for some legacy code, I need to return a list of rows than come from a list of the element, but, the client needs it without the property name.
This is what I need. (I know that inside this JSON return, it's an array list then it's not a valid JSON, but is the way that needs to be received by the front end I don't know why
{ "success":true,"msg":"","draw":"1","recordsTotal":14,"recordsFiltered":14,
{ "data":
[
["Xiaomi","Redmi 8","10","6.0.1","","sadsadasd"],
["Xiaomi","Redmi 8","10","6.0.1","","sadsadasd"],
]
}
This is what I got now
{"success":true,"msg":"","draw":"1","recordsTotal":14,"recordsFiltered":14,
"data" :[
{"Brand":"Xiaomi","Model":"Redmi 8","Version":10,"App":"4.3.3","Phone":"","AsignedUSer":"ceererer"},
{"Brand":"Xiaomi","Model":"Redmi 8","Version":10,"App":"4.3.3","Phone":"","AsignedUSer":"ceererer"},
]
}
And this is the code how I am retrieving the data
return new JsonResult(new { success = true, msg = "", draw ="1", recordsTotal = listToReturn.Count(), recordsFiltered = listToReturn.Count() ,
data = listToReturn ,
});
You could project your list into arrays to extract the property values:
var data = listToReturn
.Select(d => new string[]{d.Brand, d.Model, d.Version, etc..})
.ToList();
Note that a "JSON" content without the property names will be a not valid JSON document.
What you need seems to be more like a CSV-like response.
Have you tried to format the result as CSV?
I am getting response like this from the Client :
http://192.168.25.241/CPMO.asmx?wsdl|context=
{transaction_id=9610842, ref_id=14943018526993,
service_id=CPA_MCOM_999, error_list=n/a, sub_eff_date=201705121715460,
notification_ind=2, error_code=1, destination_mobtel=0105660125,
keyword=dummy, CURRENT_STEP=0, sub_exp_date=201705131200000}
Note :
?wsdl|context=
{transaction_id=9610842, ref_id=14943018526993, service_id=CPA_MCOM_999, error_list=n/a, sub_eff_date=201705121715460, notification_ind=2, error_code=1, destination_mobtel=0105660125, keyword=dummy, CURRENT_STEP=0, sub_exp_date=201705131200000}
So How can I read this string within the {}, after reading the parameters, redirect to the particular URL (I mean above URL), Can anyone help me in C#?
You can read the string as explained below.
var text = "{transaction_id=9610842, ref_id=14943018526993, service_id=CPA_MCOM_999, error_list=n/a, sub_eff_date=201705121715460, notification_ind=2, error_code=1, destination_mobtel=0105660125, keyword=dummy, CURRENT_STEP=0, sub_exp_date=201705131200000}";
//replace {} from your string.
var dict = text.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(part => part.Split('='))
.ToDictionary(split => split[0], split => split[1]);
I'm working with an API that is returning JSON.
I have a method that calls the api, and parses the JSON response for the desired nodes.
Up to this point everything has been working fine, except the latest JSON response appears to be malformed.
Other responses come back like:
{
"Keyword":"\"marhope\"",
"TermKey":null,
"Customers":[
{
"Memberships":[ ],
"CompanyId":0,
"ObjectId":112974,
"ObjectType":"Customer",
}
]
}
I use JObject.Parse to bring back the appropriate nodes by name.
The latest JSON response comes back as:
{
[
{
"AnimalId":9079117,
"SpeciesCode":"XX",
}
]
}
As you can see, there is no "name", and the JSON is slightly invalid.
How can I parse this. For the first example I was using the code below, but now that the JSON has no "name", I don't know how to approach this, thoughts?
JObject results = JObject.Parse(csr.SearchCustomer(1, 1, 870, term));
foreach (var resp in results["Customers"])
{
string obj = (string)resp["CompanyId"];
}
Jon Skeet is correct, the second JSON is invalid: you cannot have an array directly inside an object with no property name. The best course of action is to get the API developers to fix the JSON. However, if you're just looking for a quick and dirty workaround, you could strip off the the first and last brace from the invalid JSON and then parse it as an array using JArray.Parse.
string json = #"{
[
{
""AnimalId"":9079117,
""SpeciesCode"":""XX"",
}
]
}";
json = json.Substring(1, json.Length - 2);
JArray array = JArray.Parse(json);
foreach (JObject item in array.Children<JObject>())
{
Console.WriteLine("AnimalId: " + item["AnimalId"]);
Console.WriteLine("SpeciesCode: " + item["SpeciesCode"]);
}
I am having trouble working with an API, first time I've worked with one. I've managed to use GET to read the data I need and that part is working perfectly, now I need to deserialize the JSON data I am getting back, and I am using Newtonsoft's JSON .NET library. The problem seems to come when I deserialize the data as its exploding and the debugger isn't being helpful. I tried a few suggestions online but no go, so if someone can enlighten me it'd be appreciated. This is the code:
string url = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string responseData = readStream.ReadToEnd();
var results = JsonConvert.DeserializeObject<dynamic>(responseData);
var id = results["id"].Value;
// var name = results.Name;
When I run it the debugger throws the following exception at the last line of code:
{"Accessed JArray values with invalid key value: \"id\". Array position index expected."}
I am fairly sure that ID exists in the data I am getting back.
Json data I am getting back from Smarty Streets:
[
{
"id": 0,
"candidate_index": 0,
"delivery_line_1": "1600 Amphitheatre Pkwy",
"last_line": "Mountain View CA 94043-1351",
"delivery_point_barcode": "940431351000",
"components": {
"primary_number": "1600",
"street_name": "Amphitheatre",
"street_suffix": "Pkwy",
"city_name": "Mountain View",
"state_abbreviation": "CA",
"zipcode": "94043",
"plus4_code": "1351",
"delivery_point": "00",
"delivery_point_check_digit": "0"
},
]
Your response is an array not a single object. So You should use
JArray results = JArray.Parse(responseData)
to parse the result (like results[0]["id"]). If you go the dynamic way then
dynamic results = JArray.Parse(responseData)
Now, you can use it like results[0].id
Another option is to "Paste JSON as classes" so it can be deserialised quick and easy.
Simply copy your entire JSON
In VS: Click Edit > Paste Special >
Paste JSON as classes
Here is a better explanation n piccas...
https://blogs.msdn.microsoft.com/webdev/2012/12/18/paste-json-as-classes-in-asp-net-and-web-tools-2012-2-rc/
Your result appears to be an array of objects, not an array itself. Try setting id to results["id"][0].Value and see if you get something.
See this: Accessed JArray values with invalid key value: "fields". Array position index expected
I'm using a REST Service library with C# called RestSharp. I've been trying for too long to send information to a emailforge(newsletter service) server but i couldn't make it so far. I can post, put and get basic information, but i can't do the same with fields or lists within the Json sent.
RestClient client = new RestClient();
client.BaseUrl = "https://s3s.fr/api/rest/1/";
client.Authenticator = new HttpBasicAuthenticator(splioUser, splioPass);
var request = new RestRequest("{item}", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddUrlSegment("item", "contact");
request.AddParameter("email", "test#test.com.br");
request.AddParameter("firstname", "Jhonny");
request.AddParameter("lastname", "Test");
request.AddParameter("lang", "EN");
And that's the result:
{"email":"test#test.com.br","date":"2013-12-20 18:43:42","firstname":"Jhonny","lastname":"Test","lang":"EN","fields":[{"id":"0","name":"sexo","value":""},{"id":"1","name":"nascimento","value":""},{"id":"2","name":"cidade","value":""},{"id":"3","name":"estado","value":""},{"id":"4","name":"data altera\u00e7\u00e3o do cadastro","value":""},{"id":"5","name":"data \u00faltima compra","value":""},{"id":"6","name":"data primeira compra","value":""},{"id":"7","name":"data de criacao do cadastro","value":""},{"id":"8","name":"data de ultimo login no site","value":""}],"lists":[]}
It seems that i can't include any values between "lists" and "fields" values.
There's a manual orienting how to do it using PHP:
$universe = 'testapi';
$pass = 'MySecretAPIKEY';
$resource = ‘contact‘ ;
$email = ‘old#s3s.fr’ $service_url = "https://$universe:$pass#s3s.fr/api/rest/1/$resource/$email";
$curl = curl_init($service_url);
$query = array ( 'email' => ‘newmail#s3s.fr', 'lang' => 'de', 'fields' => array ( array ( 'id' => '0', 'value' => 'bl10'), array ( 'name' => 'field2', 'value' => 'myothercustomfield_value'), ), 'lists' => array ( array ( 'name' => 'Test Api' ), array ( 'id' => '5', 'action' => 'unsubscribe' ), ), ) ;
$qstring = json_encode($query);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS,$qstring);
curl_setopt($curl,CURLOPT_HTTPHEADER,array("Expect:"));
$curl_response = curl_exec($curl);
curl_close($curl);
var_dump($curl_response);
var_dump(json_decode($curl_response, true));
Thanks in advance!
Using RestSharp, you should use the built in json serialization. See this previous answer for an example
ADDED
Also, I find that using Fiddler or a similar tool is very useful for debugging. Fiddler requires some configuration to monitor traffic for some use cases,