nil.to_json cannot be parsed back to nil?
The problem is not specifically with nil
. It's that to_json
on a simple thing like nil
or a single string doesn't produce a full JSON representation.
e.g. something like JSON.parse("hello".to_json)
would yield similar results
If we have a Hash
with nil
for one of its values it will encode and decode correctly:
>> h = {"name"=>"Mike", "info"=>nil}
=> {"name"=>"Mike", "info"=>nil}
>> h.to_json
=> "{\"name\":\"Mike\",\"info\":null}"
>> JSON.parse(h.to_json)
=> {"name"=>"Mike", "info"=>nil}
Parsing JSON in Swift with nil values
Map the property names from the JSON to your struct's members using CodingKeys
:
struct Value: Codable {
let businesses: [String]?
let customer: String?
let id: Int
let name: String
let customerID: String?
enum CodingKeys: String, CodingKey {
case businesses = "Businesses"
case customer = "Customer"
case id = "ID"
case name = "Name"
case customerID = "CustomerID"
}
}
to_json on single value can't be parse back
The problem comes from calling to_json on a single value. This doesn't produce a full JSON representation. Here is some examples:
"hello".to_json
=> "\"hello\""
JSON.parse("hello".to_json)
=> JSON::ParseError: 743: unexpected token at...
nil.to_json
=> "null"
JSON.parse(nil.to_json)
=> JSON::ParseError: 743: unexpected token at...
Fortunately, the JSON parser come with a "quirks mode" who allow to parse single values:
"hello".to_json
=> "\"hello\""
JSON.parse("hello".to_json, {:quirks_mode => true})
=> "hello"
nil.to_json
=> "null"
JSON.parse(nil.to_json, {:quirks_mode => true})
=> nil
I'm not sure of what :quirks_mode is really doing, maybe someone could explain it a bit?
Why is `JSON.parse` not throwing exception?
The functionality has been updated to comply with the JSON specification according to RFC 7159, which says:
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:false null true
The literal names MUST be lowercase. No other literal names are allowed.
So, JSON.parse("null")
returning nil
is expected functionality, which you can confirm by checking out the tests for parsing single values.
Can't parse JSON property null
The first JSON posted is valid JSON: the JSON in the Java, however, is not valid -- only "
is valid for the [required] key quote. From json.org:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes....
However, that sounds like a bug, assuming it was not triggered by the invalid JSON fed to it (the library can do whatever it wants with invalid JSON)... one would have to look at the source (or bug reports / user experience) to say conclusively if this is indeed a "bug". I have added some suggestions of things to try below which may either show expected behavior or outline the cause/issue in further detail.
Consider this minimal test-case (with valid JSON):
String st = "{ \"null\": \"hello world!\" }";
This may also shed more light, depending on if the first item is "null"
or null
when extracted:
String st = "[ \"null\" ]";
Happy coding.
Parsing JSON - null of type JSONObject cannot be converted to JSONArray
The exception is perfectly valid. Your trying to convert json object into json array. Try below code
remove "\n" character at the end.
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n")
add below logs
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
Log.debug("api_response","api-response->"+data);
and try below code
if(data!= null){ // add this if condition too.
JSONObject jsonObj = new JSONObject(data);
JSONArray myJsonArray = jsonObj.getJSONArray("result"); ; //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
Swift JSON Parsing - Unable to access field/returns nil
The closure passed as an argument in dataTaskWithRequest
is asynchronous meaning that it could be called instantly or way down the road given network conditions. It would be better to pass a closure in your original sendJsonRequest
method while return void
. Once the dataTaskWithResult
closure is called, you can invoke your closure with the response.
In terms of code, it might look like this:
func sendJsonRequest(connectionString: String,
httpMethod : HttpMethod = HttpMethod.Get,
jsonHeaders : [String : String] = [ : ],
jsonString: String = "",
completion: (data: NSData?, error: NSError?) -> Void) {
… //Your code
var urlTask = session.dataTaskWithRequest(request) { (optionalData, optionalResponse, optionalError) in
NSOperationQueue.mainQueue().addOperation {
if let data = optionalData {
completion(data, nil)
}
else if let error = optionalError {
completion(nil, error)
}
}
}
urlTask.resume()
}
// return the coordinates of a given location
func getCoordinates(withCompletion completion: (Coordinates) -> Void) {
let connectionString = "https://maps.googleapis.com/maps/api/geocode/json?address=43201"
sendJsonRequest(connectionString: connectionString) {
(optionalData, optionalError) in
if let data = optionalData {
let json = JSON(data)
print(json)
//Do your conversion to Coordinates here
let coordinates = //?
completion(coordinates)
}
// Handle errors, etc…
}
}
One note, arguments and variables are lowercased. Only class names should be uppercase.
Class array object value always return nil after json serialization
here is Version For objetive c,
@property (strong,nonatomic) NSMutableArray<UserModel *> *jsonarray ;
@end
@implementation ViewController
dispatch_group_t serviceGroup;
NSMutableDictionary *result ;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
result = [[NSMutableDictionary alloc]init];
self.tableView.delegate = self;
self.tableView.dataSource = self;
UINib *nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:@"TableViewCell"];
serviceGroup = dispatch_group_create();
_jsonarray = [[NSMutableArray alloc]init];
// \ [userdata GetDatafromUrl:@"https://jsonplaceholder.typicode.com/users"];
[self GEtDataFromurl:@"https://jsonplaceholder.typicode.com/users"];
}
-(void)GEtDataFromurl:(NSString *) urlstr{
dispatch_group_enter(serviceGroup);
[[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:urlstr] completionHandler:^(NSData *_Nullable data,NSURLResponse *_Nullable response, NSError *_error){
NSError *err;
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
if(err){
NSLog(@"Falied to serialization.. ");
return;
}
for (NSDictionary *UserDir in json){
NSString *Id = UserDir[@"id"] ;
NSString *name = UserDir[@"name"] ;
NSString *username = UserDir[@"username"];
NSString *email = UserDir[@"email"];
NSString *phone = UserDir[@"phone"];
NSString *website = UserDir[@"website"];
struct company *company = CFBridgingRetain(UserDir[@"company"]);
struct address *address = CFBridgingRetain(UserDir[@"address"]);
UserModel *model = UserModel.new;
model.Id = [Id intValue];
model.name = name;
model.address = address;
model.username = username;
model.email = email;
model.phone = phone;
model.website = website;
model.company = company;
NSLog(@"%@", model.name);
[_jsonarray addObject:model];
}
dispatch_group_leave(serviceGroup);
}]resume];
dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
NSLog(@" outside user class : %@", _jsonarray);
[self.tableView reloadData];
});
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell" forIndexPath:indexPath];
if(cell == nil){
NSArray *obj = [[NSBundle mainBundle] loadNibNamed:@"TableViewCell" owner:self options:nil];
cell = [obj objectAtIndex:0];
}
UserModel *model = _jsonarray[indexPath.row];
cell.displaylabel.text = model.username;
return cell;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
return _jsonarray.count;
}
@end
Related Topics
You Don't Have Write Permissions into the /Var/Lib/Gems/1.9.1 Directory
Ruby - Does Array a Contain All Elements of Array B
Access Ruby Hash Using Dotted Path Key String
Creating a Test Suite Using Ruby Minitest
Cannot Load Such File -- Rack/Handler/Puma
How to Use Link_To to Link an Image and a Text
Error Running Heckle? 'Current_Code': Undefined Method 'Translate' for Ruby2Ruby
Detecting If This Is an Iframe Load or Direct
What Are Some Good Role Authorization Solutions Used with Authlogic
How to Programmatically Check If a Certificate Has Been Revoked
Installing Libyaml for Ruby on a MAC Osx (Lion)
Setting Mime Type for .Ogv Files in Rails Development Environment
How to Tell Which Openssl Lib Is Actually Being Used by an Rvm-Installed Ruby
Trying to Set Up Amazon's S3 Bucket: 403 Forbidden Error & Setting Permissions