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');
Related
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
This is a really weird bug, when grabbing JSON from my server (which is produced via PHP), I get this error when calling:
json = [NSJSONSerialization JSONObjectWithData:kivaData
options:kNilOptions
error:&jsonError];
JSON Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x178467d00 {NSDebugDescription=Garbage at end.}
My (NSData* kivaData) grabs everything perfectly, but it cant parse the JSON.
I have run my JSON code in http://jsonlint.com/ and it comes out Valid everytime.
Its really weird because it can parse the JSON when I connect to Wifi, but when I try doing it via cellular, it wont work. It does work over cellular on some peoples phones, but every time.
using swift 4, first of all check the JSON Data using print :
print (String(data:data!, encoding: .utf8)!)
check for the white spaces or unwanted characters, then remove them :
var string = String(data: data!, encoding: .utf8)
string = string?.replacingOccurrences(of: "/r/n", with: "")
after that, assign the string back to data variable :
let data1 = string!.data(using: .utf8)
encoding is very important. If your json is valid, the issue might be you have special characters in your json data, which is not correctly parsed by the json serializer. When you send the data, make sure you have the correct url-encoding when sending content so client will parse it correctly. Using utf-8 always or base64.
I was able to solve the same problem (works on wifi, but not on carrier network) by sending a content-length header just before the response:
header("Content-length: ".strlen($response));
echo $response;
exit;
I ended up having to change my php file from echoing the json syntax to simply outputting with json_encode.
JsonData is usually stored in dictionary format. Since the json is not able to parse the continuous data[its not able to separate the responses] its throwing this error .
You can maintain a dictionary to store the responses obtained from server .
Each task will have a unique response . So create a dictionary with "keys" as "taskIdentifier" of tasks and "values" as "data".
Eg:
Inside didReceiveData or any other equivalent methods [where you get response from server ] store response in dictionary with taskIdentifier as keys .
NSString *taskID = [#(dataTask.taskIdentifier) stringValue];
[_task_data_dictionary setObject:data forKey:taskID];
Here _task_data_dictionary is the dictionary.In this way you can get rid of the above error .
After this you can get data using the same dictionary using this code
NSData *data = [_task_data_dictionary objectForKey:taskNumber];
again using the taskIdentifier .
Hope this helps .
I want to know how to convert a string of compact Json to pretty print so that I can parse it. I have searched for this question in stack overflow but it doesn't seem like anyone has asked it for codename one.
Right now I have a string of compact Json but it can not be parsed. This is the code:
String JsonData = "{\"document\":{ \"type\":\"PLAIN_TEXT\", \"content\":\"Ask not what your country can do for you, ask what you can do for your country.\" },\"encodingType\":\"UTF8\"}";
JsonResponse = Rest.
post("https://language.googleapis.com/v1/documents:analyzeSyntax?key=[API KEY").
jsonContent().
body(JsonData).
getAsJsonMap();
String JsonString = (JsonResponse.getResponseData()).toString();
JSONParser parser = new JSONParser();
Map<String, Object> results = null;
try {
results = parser.parseJSON(new StringReader(JsonString));
} catch (IOException e) {
e.printStackTrace();
System.out.println("fail");
}
System.out.println("results "+results);
But when I run this code I get a bunch of these responses:
[EDT] 0:0:3,269 - Expected null for key value while parsing JSON token at row: 1 column: 5 buffer: e
and
java.lang.NumberFormatException: For input string: "ee0"
How should I convert my string of compact Json (JsonString) to pretty print so that I can parse it? Alternatively, is there a way to directly parse the response (JsonResponse)?
Thank You
You are printing out a map not a JSON string as the JSON data is already parsed. If you just want to look at the network protocol for debugging the best way to do that is open the Network Monitor in the simulator where you will see all HTTP requests and can copy out the response body JSON.
However you can still convert a Map back to JSON using:
Log.p("results " + JSONParser.mapToJson(results));
Notice you should use Log.p() and Log.e() to log strings/exceptions as that would work better on the devices.
I am using SwiftyJson. I am getting a response from printing.
{ "coin" : 120 }
I want to store this response in a variable. How can I store this value in a variable?
To get the specific value from response, it's related with type of response.
https://grokswift.com/json-swift-4/
For example, if response is JSON Array, Please try this.
let val = response[index][key]
otherwise,
let val = response[key1][key2][..]
I'm having trouble parsing the following JSON file with SwiftyJSON. I've looked around the web and tried different suggested solutions with no luck.
Here is the JSON:
{'info-leag':{'Status':1,'Name':'Testing Name','url-lig':'test.testing.com','uid':'12345'}}
And my relevant code:
//initializes request
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, maybeData, error in
if let data = maybeData {
let json = JSON(data: data)
//stores data as UTF8 String
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
The first part seems to work fine, I am able to get the JSON and save it as data, at the bottom I converted it to a string to make sure that I was getting the right information, I then later print it to make sure.
I tried different things like:
let name = json["info-league"]["Name"] //can't seem to get the context
I'm trying to get the Name and uid to be saved as 2 strings as well as the Status as an int.
Thanks!
Once you've made your JSON valid like this:
{"info-league":{"Status":1,"Name":"Testing Name","url-lig":"test.testing.com","uid":"12345"}}
you will be able to use your example, it works (I just tested):
let name = json["info-league"]["Name"]
but it's better to use SwiftyJSON types:
let name = json["info-league"]["Name"].string
let status = json["info-league"]["Status"].int
so your variables are of known types for later use.
If you don't do this they will be of type JSON, a type created by SwiftyJSON, and you will have to cast them later (not a problem, depends how you're organised in your code).
Try:
let name = json["info-league"]["Name"].string