anyone know how to send JSON in ActionScript 2?
I tried using XML() but it changes all " into " before sending it. Ex:
var callout = new XML({ "name": "John"})
callout.sendAndLoad('http://api.app.com', new XML());
but what gets sent is { "name": "John"}
also cannot upgrade to AS3 (wish i could)
Here's how you do it
Create a new class that extends LoadVars and override the "toString" method to return the JSON. You can then use load() and sendAndLoad() to send JSON to an URL
Example:
class SendJson extends LoadVars {
public var data:String; // Put your JSON here
public function toString() {
return data;
}
}
Related
I want to append a certain "id" to an api. This is the initial portion of how I make the API call in my viewController..
func myAPICall() {
APIHelper(API: WebServices.getAllOrganizations as NSString, json: bodyStr as NSString,
methodType: Constants.Get_Method as NSString....)
}
Now, WebServices.getAllOrganizations is defined elsewhere, in a swift file like so...
public class WebServices {
static let getAllOrganizations: String = "organization/getAllOrganizationDetails
}
MY ATTEMPT TO PASS THE ID TO THE SWIFT FILE :
To pass the value, I assigned it to a global variable like so...
ArrayData.shared.plantIDForOrganization = Int("\(dic["id"]!)")!
And further, I changed my swift file to this...
public class WebServices {
static let getAllOrganizations: String = "organization/getAllOrganizationDetails/\(ArrayData.shared.plantIDForOrganization)"
}
But by doing this, the value is not properly passed to the API. A 0 is passed to the API instead of the actual id number.
What could be a more efficient way of passing value from my viewcontroller to the swift file..?
When is ArrayData.shared.plantIDForOrganization initialized, and when does WebServices.getAllOganizations get its value? Once the latter is set, it won't "react" to changes in plantIDForOrganization.
I suggest you change this to a computed property, like so:
public class WebServices {
static var getAllOrganizations: String {
return "organization/getAllOrganizationDetails/\(ArrayData.shared.plantIDForOrganization)"
}
}
Also, try to eliminate thos force-unwrapping from your code.
If you have to pass a parameter use a static method instead:
public class WebServices {
static func getAllOrganizations(id: String) -> String { "organization/getAllOrganizationDetails/\(id)" }
}
I have two Futures which load a String from a JSON File for me. My Goal is to have a class Data within which, I can hold different objects (for example Feed). What I don't understand right now, is how I write a class data which can hold the object feed, as well as, load the feed object from the Future.
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'package:freeletics_insights/feed.dart';
Future<String> _loadFeedAsset() async {
return await rootBundle.loadString('assets/json/userfeed1.json');
}
Future<Feed> loadFeed() async {
String jsonFeed = await _loadFeedAsset();
final jsonResponse = json.decode(jsonFeed);
Feed feed = new Feed.fromJson(jsonResponse);
//print(feed.feedEntries.length);
return feed;
}
class Data {
Feed feed;
Data.loadData(){
this.feed = loadFeed();
}
}
void main{
var data = Data.loadData();
print(data.feed.feedEntries.length);
}
I alway get an error that the type
FutureFeed
cannot be assigned to a type Feed.
This is something that used to slip me up a bit when I first started using Dart and Flutter. Your loadFeed() method returns a type of Future<Feed> but your Data classes member feed is of type Feed, which are two different types. What you want to do is "unwrap" the Future<Feed> returned from your loadFeed() method in order to access the Feed object.
You "unwrap" Future objects using the async/await syntax.
What it might look like you can do is:
class Data {
Feed feed;
Data.loadData() async {
this.feed = await loadFeed();
}
}
... but you loadData() is a constructor of Data and you can't have constructor methods marked as async. You can however mark you main() method as async to use async/await syntax to unwrap your Future<Feed>.
The only thing I've changed in your code is added your feed member of Data to the constructor and adapted your main() method to asyncronously load your feed and pass the result into the constructor of your Data object.
Future<String> _loadFeedAsset() async {
return await rootBundle.loadString('assets/json/userfeed1.json');
}
Future<Feed> loadFeed() async {
String jsonFeed = await _loadFeedAsset();
final jsonResponse = json.decode(jsonFeed);
Feed feed = new Feed.fromJson(jsonResponse);
//print(feed.feedEntries.length);
return feed;
}
class Data {
Feed feed;
Data(this.feed);
}
void main async {
var feed = await loadFeed();
var data = Data(feed);
print(data.feed.feedEntries.length);
}
I have a web-service which returns student and enrolled class details.
{
"name": "student-name",
"classes": [
{
"className": "reactor-101",
"day": "Tuesday"
},
{
"className": "reactor-102",
"day": "Friday"
}
]
}
The DTO for this class is as below:
public class Student {
private String name;
private Flux<StudentClass> classes;
#Data
#AllArgsConstructor
#JsonInclude(JsonInclude.Include.NON_DEFAULT)
public static class StudentClass {
private String className;
private String day;
}
}
The main REST controller logic to fetch the student is as follows:
Flux<StudentClass> studentClassFlux = studentClassRepository.getStudentClass(studentName);
return Mono.just(new Student(studentName, studentClassFlux));
The problem with this is, I get the following output after making the REST call:
{
"name": "student-name",
"classes": {
"prefetch": 32,
"scanAvailable": true
}
}
I can achieve the desired output by blocking on the flux request to get completed and then convert the output to list.
List<StudentClass> studentClassList = studentClassRepository.getStudentClass(studentName)..toStream().collect(Collectors.toList());
return Mono.just(new Student(studentName, studentClassList)); // Change the Student#classes from flux to list
I am new to reactive-programming.
What is the correct way of using the Flux & Mono here to get the desired output?
Reactive types aren't meant to be serialized when wrapped in each other.
In that particular case, you probably want your Student object to contain a List<StudentClass>. You can achieve that like this:
public Mono<Student> findStudent(String studentName) {
return studentClassRepository
.getStudentClass(studentName)
.collectList()
.map(studentClasses -> new Student(studentName, studentClasses));
}
I think, in the case that you really need a Flux in your result, you would want to break down the API so that you have separate methods to retrieve the entities.
One for student properties, and another for their classes. The student GET method could be a Mono, while the classes would return a Flux.
I am doing a POC for Command object in Grails Controller and i face a road block where the binding doesn't happen.
Command Object
public class Employee {
String name;
int age;
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Controller :
class EmployeeController {
def index() {
render (" Employee Index Called ");
}
def emp(Employee employee){
println( employee.toString());
render(" Success");
}
}
I am calling emp action from a rest client as below
Method: POST
URL : http://localhost:8080/Grails/employee/emp
Request Body : { "name": "Vinod", "age": 34 }
I get employee.name as null and employee.age=0 always
I am suspecting my Request Body is wrong but not sure. Please help where I am going wrong.
Thanks
As far as I know, json is not bound automatically to command object (defined as action method arg), only plain params are. To get a hold on JSON request you have to call
def json = request.JSON
and then you can try binding it to your object:
def co = new MyCommandObject( json )
For POST request method, I had to set 'Content-Type' header as 'application/json'
Grails constructs command object from JSON in request body of POST(JSON to Java Object)
Whenever Grails finds 'Content-Type' header as 'application/json' it will automatically parse the request body in JSON to command object and pass it on to the controller method.
You may also want to make the command class validatable by doing the following.
In Grails 3:
Your command class can to implement grails.validation.Validateable trait.
import grails.validation.Validateable
class Employee implements Validateable{
String name
int age
}
In Grails 2.x:
You command class can have grails.validation.Validateable annotation
#grails.validation.Validateable
class Employee implements Validateable{
String name
int age
}
I'm having a tree of domain classes that i want to convert to JSON via a deep converter:
import grails.converters.deep.JSON
deepObject as JSON
Somewhere in the tree I'm having Double.NaN values in some fields and the JSON parser throws an exception:
org.apache.commons.lang.UnhandledException: org.codehaus.groovy.grails.web.converters.exceptions.ConverterException: org.codehaus.groovy.grails.web.json.JSONException: JSON does not allow non-finite numbers
How can I handle that case? May be returning a string ('NaN').
I tried repacing the JSONObject.testValidity(Object o) method, but this is a pojo and so it does not work.
Edit
I also tried to register a marshaller in Bootstrap.groovy:
JSON.registerObjectMarshaller(Double) {
return it == Double.NaN ? 'NaN' : it.toString()
}
But it also wont work.
Unfortunately most native values rendering is hardcoded in grails.converters.JSON, and can't be personalized with registerObjectMarshaller. One solution is to specify the JSON converter class and override its value(Object o) method as:
import grails.converters.JSON
class MyJSONConverter extends JSON {
#Override
public void value(Object o) throws ConverterException {
if (o instanceof Double && o.NaN)
o = 'Nan'
super.value(o);
}
}
and call your custom implementation with
import org.grails.web.converters.ConverterUtil
import org.grails.web.servlet.mvc.GrailsWebRequest
MyJSONConverter myJSONConverter = ConverterUtil.createConverter( MyJSONConverter.class, deepObject, GrailsWebRequest.lookup()?.applicationContext);
String deepString = myJSONConverter as String;