GetCapabilities Query for TileServer Returns Malformed JSON - json

I have installed TileServer.php. When I navigate to it, I can see my tiles (so it's working).
My issue is when I query for the getCapabilities file the resulting json file is malformed.
The json is prefixed with part of the query string at the start of the json response.
Here is the full query string:
http://<=my ip=>/tileserver/index.html?service=wmts&request=getcapabilities&version=1.0.0
Actual Json Response I Receive
(Notice wmts&request is prefixed to the otherwise valid json)
====JSON===============================
wmts&request([{"name":"190322","type":"overlay","description":"190322","version":"1.1","format":"png","bounds":[174.92249449474565,-36.991878207885335,174.93635413927785,-36.98244705946717],"maxzoom":22,"minzoom":14,"basename":"1313_190322","profile":"mercator","scale":1,"tiles": ...
==================================================
I have tried removing part of the query string to test for the results, oddly enough it grabs the part of the query string again.
Here is the full query string I tested with:
http://<=my ip=>/tileserver/index.html?request=getcapabilities&version=1.0.0
(Actual Json Response I Receive)
====JSON===============================
getcapabilities&version([{"name":"190322","type":"overlay","description":"190322","version":"1.1","format":"png","bounds":[174.92249449474565,-36.991878207885335,174.93635413927785,-36.98244705946717],"maxzoom":22,"minzoom":14,"basename":"1313_190322","profile":"mercator","scale":1,"tiles": ...
=======================================================
I could parse this out I suppose but I would like to find the cause for this issue.
I am using ASP.Net 5.0.
Here is roughly my code:
private static readonly string _tileserver_ip = "http://<my ip>/tileserver/";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var query = new Dictionary<string, string>
{
["service"] = "wmts",
["request"] = "getcapabilities",
["version"] = "1.0.0"
};
var response = await client.GetAsync(QueryHelpers.AddQueryString(_tileserver_ip, query));
var capabilitiesString = await response.Content.ReadAsStringAsync();
// the result of the query string => "http://<my ip>/tileserver/?service=wmts&request=getcapabilities&version=1.0.0"
EDIT
Opps! Turns out I was requesting the getCapabilities file from the TileServer in the completely wrong way.
I will leave this here encase it helps someone in the future.
Here is the correct URL: http://<= my url =>/tileserver/1.0.0/WMTSCapabilities.xml/wmts

I found the answer and I will leave this post here encase it helps someone in the future.
In my URL I was using index.html as the index page, however I should have been using index .json instead.
As soon as I switched to .json I received the JSON response as I was expecting.
Full URL with query string:
http://<=my ip=>/tileserver/index.json?service=wmts&request=getcapabilities&version=1.0.0

Related

(Not-Json data + Json data) to Json data

I got my data from the server. I need to JSON decode them, before I use it. The problem is, the response data contains some extra text data too. So, when I use
String/ Iterable decodedData = json.decode(responseData)/ jsonDecode(responseData);
It gives me an error:
SyntaxError: Unexpected token < in JSON at position 0
My response from the server:
Message has been sent{"unique_id":"2021080504511401","role_id":3,"category_id":"1","first_name":"Nasir","phone":"23423423430","nid":"234234234","f_name":"sadfasdf","blood_group":"AB+","profession":"Farmer","gender":"female","address":"asdfasdfasdf","image":null,"district_id":null,"upazilla_id":"1","union_id":null,"email":"alskdsfjserdf#gmail.com","updated_at":"2021-08-05T10:51:14.000000Z","created_at":"2021-08-05T10:51:14.000000Z","id":60}
I need to get the object only. I can remove the non-used string data by accessing the index. But what if the text before the object is dynamic? I need a stable solution now.
I prepared an example for you, I hope it solves your problem.
final response = '''
Message has been sent{"unique_id":"2021080504511401","role_id":3,"category_id":"1","first_name":"Nasir","phone":"23423423430","nid":"234234234","f_name":"sadfasdf","blood_group":"AB+","profession":"Farmer","gender":"female","address":"asdfasdfasdf","image":null,"district_id":null,"upazilla_id":"1","union_id":null,"email":"alskdsfjserdf#gmail.com","updated_at":"2021-08-05T10:51:14.000000Z","created_at":"2021-08-05T10:51:14.000000Z","id":60}
''';
final objectStartIndex = response.indexOf('{');
final objectData = response.substring(objectStartIndex);
final decodedData = jsonDecode(objectData);
print('Result: $decodedData');

Remove first line of json file before getting data with Dio

I have a json file that I'm getting from the web that starts with the characters )]}',. Example:
)]}',
{<DATA START HERE>}
I want to read this data with Response response = await dio.get(url);, but the first line of that json file is causing errors. How can I tell dio to skip the first line?
That's rather strange. I wonder if it's some special guard characters generated by the server. Ask them why they add it.
That said, as long as it's the same pattern each time, it looks like the garbage is on a different line from the json. So, just split the string and pick up the second line.
Here's an example using http. Adapt it for dio if you prefer that.
main() async {
http.Response response = await http.get(
'https://25live.collegenet.com/25live/data/umd/run/availability/availabilitydata.json?etc');
String val = response.body;
String validJson = val.split('\n')[1];
Map<String, dynamic> decodedJson = json.decode(validJson);
print(decodedJson);
}

No content when using PostAsync to post JSON

Using the code below, I've managed to create a jsonArray with the following format:[{"id":3},{"id":4},{"id":5}]
var jArray = new JsonArray();
int numOfChildren = 10;
for (int i = 0; i < numOfChildren; i++)
{
if (CONDITION == true)
{
var jObj = new JsonObject();
int id = SOMEID;
jObj.SetNamedValue("id", JsonValue.CreateNumberValue(id));
jArray.Add(jObj);
}
I am now trying to send "JsonArray" to a server using PostAsync as can be seen below:
Uri posturi = new Uri("http://MYURI");
HttpContent content = new StringContent(jArray.ToString(), Encoding.UTF8, "application/json");
System.Net.Http.HttpResponseMessage response = await client.PostAsync(postUri, content);
On the server side of things though, I can see that the post request contains no content. After digging around on the interwebs, it would seem that using jArray.ToString() within StringContent is the culprit, but I'm not understanding why or if that even is the problem in the first place. So, why is my content missing? Note that I'm writing this for UWP aplication that does not use JSON.net.
After much digging, I eventually Wiresharked two different applications, one with my original jArray.ToString() and another using JSON.net's JsonConver.SerializeObject(). In Wireshark, I could see that the content of the two packets was identical, so that told me that my issue resided on the server side of things. I eventually figured out that my PHP script that handled incoming POST requests was too literal and would only accept json posts of the type 'application/json'. My UWP application sent packets of the type 'application/json; charset=utf-8'. After loosening some of my content checking on the server side a bit, all was well.
For those who are looking to serialize json without the use of JSON.net, jsonArray.ToString() or jsonArray.Stringify() both work well.
You should use a Serializer to convert it to string.
Use NewtonSoft JSON Nuget.
string str = JsonConvert.SerializeObject(jArray);
HttpContent content = new StringContent(str, Encoding.UTF8, "application/json");
System.Net.Http.HttpResponseMessage response = await client.PostAsync(postUri, content);

How to get Slurpable data from REST client in Groovy?

I have code that looks like this:
def client = new groovyx.net.http.RESTClient('myRestFulURL')
def json = client.get(contentType: JSON)
net.sf.json.JSON jsonData = json.data as net.sf.json.JSON
def slurper = new JsonSlurper().parseText(jsonData)
However, it doesn't work! :( The code above gives an error in parseText because the json elements are not quoted. The overriding issue is that the "data" is coming back as a Map, not as real Json. Not shown, but my first attempt, I just passed the parseText(json.data) which gives an error about not being able to parse a HashMap.
So my question is: how do I get JSON returned from the RESTClient to be parsed by JsonSlurper?
The RESTClient class automatically parses the content and it doesn't seem possible to keep it from doing so.
However, if you use HTTPBuilder you can overload the behavior. You want to get the information back as text, but if you only set the contentType as TEXT, it won't work, since the HTTPBuilder uses the contentType parameter of the HTTPBuilder.get() method to determine both the Accept HTTP Header to send, as well was the parsing to do on the object which is returned. In this case, you need application/json in the Accept header, but you want the parsing for TEXT (that is, no parsing).
The way you get around that is to set the Accept header on the HTTPBuilder object before calling get() on it. That overrides the header that would otherwise be set on it. The below code runs for me.
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6')
import static groovyx.net.http.ContentType.TEXT
def client = new groovyx.net.http.HTTPBuilder('myRestFulURL')
client.setHeaders(Accept: 'application/json')
def json = client.get(contentType: TEXT)
def slurper = new groovy.json.JsonSlurper().parse(json)
The type of response from RESTClient will depend on the version of :
org.codehaus.groovy.modules.http-builder:http-builder
For example, with version 0.5.2, i was getting a net.sf.json.JSONObject back.
In version 0.7.1, it now returns a HashMap as per the question's observations.
When it's a map, you can simply access the JSON data using the normal map operations :
def jsonMap = restClientResponse.getData()
def user = jsonMap.get("user")
....
Solution posted by jesseplymale workes for me, too.
HttpBuilder has dependencies to some appache libs,
so to avoid to add this dependencies to your project,
you can take this solution without making use of HttpBuilder:
def jsonSlurperRequest(urlString) {
def url = new URL(urlString)
def connection = (HttpURLConnection)url.openConnection()
connection.setRequestMethod("GET")
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty("User-Agent", "Mozilla/5.0")
new JsonSlurper().parse(connection.getInputStream())
}

RestSharp: get JSON string after deserialization?

using RestSharp is there a way to get the raw json string after it has been deserialized into an object? I need that for debugging purposes.
I'd like to see both the deserialized object and the originally received json string of that object. It's part of a much bigger json string, an item in an array and I only need that specific item json code that's got deserialized into the object.
To help you out this should work, this is a direct example of some of my work, so your's might be a bit different.
private void restClient()
{
string url = "http://apiurl.co.uk/json";
var restClient = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddParameter("apikey", "xxxxxxxxxx");
restClient.ExecuteAsync<Entry>(request, response =>
{
lstboxtop.Items.Add(response.Content);
});
}
The line lstboxtop is a listbox and using the response.content will literally print the whole api onto your app, if you call it first that would be what you are looking for