convert class to object actionscript 3 - json

I`m tring to covert class to json.
The class is:
package com.globalData{
public class userSite {
private var uID:int,uName:String,uSocket:int,uZone:int,uRoom:int;
public function user(ID:int,Name:String,ZoneID:int,RoomID:int,socketID:int){
uID = ID;
uName = Name;
uSocket = socketID;
uZone = ZoneID;
uRoom = RoomID;
}
public function getName():String{
return uName;
}
public function getID():int{
return uID;
}
public function getZoneID():int{
return uZone;
}
public function getRoomID():int{
return uRoom;
}
public function getSocket():int{
return uSocket;
}
}
}
Im tryed to do:
json(Object(roomVar));
But its not work (JSOn is function on the main class)
Im need to convert the class to json and send the json -> Socket
How can i do it?

There are a few issues with your code above:
It doesn't appear as though your userSite class has a constructor. Instead, you've opted to have a user function that takes in all of the initialization arguments
You're using functions where you should probably be using accessor methods, sometimes called a getter.
public function getName():String { return uName;} would become public function get name():String { return uName;}
Instead of calling getName(), you would access name as a property: instance.name
You're attempting to pass an Object to the JSON.decode method, this method expects a String. Something like "{ 'a':1, 'b':[1,2,3] }" would be an acceptable parameter. This would return an object with two properties a and b, a would contain the value 1, and b would contain an array with the elements 1, 2, and 3. What you are looking for is actually the JSON.encode method which accepts an Object and converts it to a String (which can be parsed as JSON).
I suggest you convert all of your getXYZ() functions to accessors, this will allow an instance of that class to be read as a collection of properties, which will in turn allow the JSON.encode function to create a JSON string object from it:
package com.globalData
{
public class UserSite {
private var uID:int,uName:String,uSocket:int,uZone:int,uRoom:int;
public function UserSite(ID:int,Name:String,ZoneID:int,RoomID:int,socketID:int):void{
uID = ID;
uName = Name;
uSocket = socketID;
uZone = ZoneID;
uRoom = RoomID;
}
public function get name():String{
return uName;
}
public function get ID():int{
return uID;
}
public function get zoneID():int{
return uZone;
}
public function get roomID():int{
return uRoom;
}
public function get socket():int{
return uSocket;
}
}
}
Usage:
var roomVar:UserSite = new UserSite(1, 'Name', 2, 3, 4);
trace(JSON.encode(roomVar as Object));
Output:
{"ID":1,"name":"Name","socket":4,"roomID":3,"zoneID":2}

Related

Reading JSON values from web browser?

I have a random JSON generated online and I am able to print all the values. But how do I read each array separately? For example, the below JSON contains different attributes, how do I read the string name that is an array containing 4 values.
JSON reader:
public class JsonHelper
{
public static T[] getJsonArray<T>(string json)
{
string newJson = "{ \"array\": " + json + "}";
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson);
return wrapper.array;
}
[System.Serializable]
private class Wrapper<T>
{
public T[] array;
}
}
[System.Serializable]
public class RootObject
{
public string name;
public string height;
public string mass ;
}
The below script is used to access the JSON online through RESTApi GET service. I am able to receive the whole text but how I read one single value of name or height or mass?
Script:
using UnityEngine.Networking;
using System.Linq;
using System.Linq.Expressions;
using UnityEngine.UI;
using System.IO;
public class GetData : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine(GetNames());
}
IEnumerator GetNames()
{
string GetNameURL = "https://swapi.co/api/people/1/?format=json";
using(UnityWebRequest www = UnityWebRequest.Get(GetNameURL))
{
// www.chunkedTransfer = false;
yield return www.Send();
if(www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
if(www.isDone)
{
string jsonResult = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(jsonResult); //I am getting the result here
}
}
}
}
}
Your API call to 'https://swapi.co/api/people/1/?format=json' returns a single object, not an array.
So after you get your json, you can access name and height etc like:
if (www.isDone)
{
string jsonResult = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(jsonResult); //I am getting the result here
RootObject person = JsonUtility.FromJson<RootObject>(jsonResult);
// then you can access each property
Debug.Log(person.name);
Debug.Log(person.height);
}

Struts2 Convert json array to java object array - not LinkedHashmap

First off my question is very similar to below however I'm not sure if the answers are applicable to my specific problem or whether I just need clarification about how to approach it:
Convert LinkedHashMap<String,String> to an object in Java
I am using struts2 json rest plugin to convert a json array into a java array. The array is sent through an ajax post request and the java receives this data. However instead of being the object type I expect it is received as a LinkedHashmap. Which is identical to the json request in structure.
[
{advance_Or_Premium=10000, available=true},
{advance_Or_Premium=10000, available=true},
{advance_Or_Premium=10000, available=true}
]
The data is all present and correct but just in the wrong type. Ideally I want to send the data in my object type or if this is not possible convert the LinkedHashMap from a list of keys and values into the object array. Here is the class I am using, incoming data is received in the create() method:
#Namespace(value = "/rest")
public class OptionRequestAction extends MadeAbstractAction implements ModelDriven<ArrayList<OptionRequestRest>>
{
private String id;
ArrayList<OptionRequestRest> model = new ArrayList<OptionRequestRest>();
public HttpHeaders create()
{
// TODO - need to use model here but it's a LinkedHashmap
return new DefaultHttpHeaders("create");
}
public String getId()
{
return this.id;
}
public ArrayList<OptionRequestRest> getModel()
{
return this.model;
}
public ArrayList<OptionRequestRest> getOptionRequests()
{
#SuppressWarnings("unchecked")
ArrayList<OptionRequestRest> lReturn = (ArrayList<OptionRequestRest>) this.getSession().get("optionRequest");
return lReturn;
}
// Handles /option-request GET requests
public HttpHeaders index()
{
this.model = this.getOptionRequests();
return new DefaultHttpHeaders("index").lastModified(new Date());
}
public void setId(String pId)
{
this.id = pId;
}
public void setModel(ArrayList<OptionRequestRest> pModel)
{
this.model = pModel;
}
// Handles /option-request/{id} GET requests
public HttpHeaders show()
{
this.model = this.getOptionRequests();
return new DefaultHttpHeaders("show").lastModified(new Date());
}
}
One of the things which is confusing me is that this code works fine and returns the correct object type if the model is not an array. Please let me know if my question is not clear enough and needs additional information. Thanks.

Converting A plain old object to value object

I think Im having a really noob moment, Im returning a remote object from coldfusion and I want to specify the object type. i.e Im getting an worker from coldfusion and I have a Value object Worker.
Heres what I have been trying
public function ResultHandler_GetWorker(event:ResultEvent):void
{
var result:ArrayCollection = ArrayCollection(event.result);
var worker:WorkerVO = WorkerVO(result[0]);
model.worker = worker;
}
Result[0] is an employee object. Its structure from debug looks like this.
workerAddress "24b fake Ave"
workerCity "Wellton"
workerCountry "Ameriland"
workerEmail "Afake#me.com"
workerFName "Foo"
workerHPhone "435234"
workerID 1
workerImage null
workerIsAdmin true
workerLName "Foo"
workerMPhone "827271903"
workerPassword "password"
workerPosition "Leader"
workerState ""
workerSuburb "Birkenhead"
workerWPhone null
my class looks like this:
public class WorkerVO
{
public var _workerAddress:String
public var _workerCity:String
public var _workerCountry:String
public var _workerEmail:String
public var _workerFName:String
public var _workerHPhone:String
public var _workerID:uint;
public var _workerImage:String
public var _workerIsAdmin:Number;
public var _workerLName:String
public var _workerMPhone:String;
public var _workerPassword:String;
public var _workerPosition:String;
public var _workerState:String;
public var _workerSuburb:String;
public var _workerWPhone:String;
public function WorkerVO()
{
}
//Getters & Setters
}
Error #1034: Type Coercion failed: cannot convert Object#114eeb251 to com.cavej03.sitesafe.vo.WorkerVO.
Am I doing it completely wrong. Am I simply meant to make a function or constructor that accepts this object and maps its fields to a new WorkerVO
You're missing a RemoteClass metadata tag. This tag tells your application which server-side VO a given client-side VO is mapped to.
Use it like this:
[RemoteClass(alias="path.to.WorkerVO")] //this is the servers-side path
public class WorkerVO {
...
}
Furthermore from what you're showing it looks like the names of your properties don't match: the client-side one has prepended underscores while the server-side one doesn't.
The property names of the client-side VO and the server-side one should be exactly the same. For instance:
/* Java VO */
public class WorkerVO {
private String workerAddress;
public String getWorkerAddress() {
return workerAddress;
}
public void setWorkerAddress(String workerAddress) {
this.workerAddress = workerAddress;
}
}
/* ActionScript VO */
[RemoteClass(alias="path.to.WorkerVO")]
public class WorkerVO {
public var workerAddress:String;
}
This is an example with a Java VO, but the same applies to ColdFusion.
Assign the returned object to a property within WorkerVO, and prepare getters for each of them like so:
public class WorkerVO
{
private var _base:Object;
public function WorkerVO(base:Object)
{
_base = base;
}
public function get address():String{ return _base.workerAddress; }
public function get city():String{ return _base.workerCity; }
// Etc.
}
And the definition of a worker just needs the new keyword added:
var worker:WorkerVO = new WorkerVO(result[0]);
trace(worker.address);

How to serialize Json string in apex

I need to parse this json string to values.
"start": { "dateTime": "2013-02-02T15:00:00+05:30" }, "end": { "dateTime": "2013-02-02T16:00:00+05:30" },
The problem is I am using JSONParser in apex (salesforce).
And my class is:
public class wrapGoogleData{
public string summary{get;set;}
public string id{get;set;}
public string status;
public creator creator;
public start start;
public wrapGoogleData(string entnm,string ezid,string sta, creator c,start s){
summary= entnm;
id= ezid;
status = sta;
creator = c;
start = s;
}
}
public class creator{
public string email;
public string displayName;
public string self;
}
public class start{
public string datetimew;
}
I am able to get all the datat from this except the datetime in the above string. As datetime is a reserved keyword in apex so i am not able to give the variable name as datetime in my class.
Any suggestion !!
Json Parser code:
JSONParser parser = JSON.createParser(jsonData );
while (parser.nextToken() != null) {
// Start at the array of invoices.
if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
while (parser.nextToken() != null) {
// Advance to the start object marker to
// find next invoice statement object.
if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
// Read entire invoice object, including its array of line items.
wrapGoogleData inv = (wrapGoogleData)parser.readValueAs(wrapGoogleData.class);
String s = JSON.serialize(inv);
system.debug('Serialized invoice: ' + s);
// Skip the child start array and start object markers.
//parser.skipChildren();
lstwrap.put(inv.id,inv);
}
}
}
}
Similar to Kumar's answer but without using an external app.
Changing your start class was the right idea
public class start{
public string datetimew;
}
Now, just parse the JSON before you run it through the deserializer.
string newjsondata = jsonData.replace('"dateTime"','"datetimew"');
JSONParser parser = JSON.createParser(newjsondata);
while (parser.nextToken() != null) {
...
}
Use string.replace() function and replace keys named dateTime with something like dateTime__x and then you can parse using Json.deserialize if you have converted your json to apex using json to apex convertor app on heruko platform
http://json2apex.herokuapp.com/
The above link points to an app that will convert Json into apex class and then you can use Json.serialize to parse json into apex class structure.

Passing 2 same object with different data as parameters, but only get the 2nd(last) object data

I'm trying to set 2 object each with different data, and pass it into another function as parameters, but when I trace for the data in the object, I can only get the 2nd object data. Seems like the 1st object was replaced by the 2nd object.
TimeSpan.betweenMonths(MyDate.setDate(1984), MyDate.setDate(1988))
The Date Object:
package hwang.time
{
public class MyDate
{
private static var _year:Number;
public static function setDate(year:Number):MyDate
{
_year = year;
return new MyDate
}
public function get year():Number
{
return _year
}
}
}
The Class the object was pass into:
public static function betweenMonths(myDate1:MyDate, myDate2:MyDate):int
{
yearArray = [myDate1, myDate2]
trace(yearArray[0].year, yearArray[1].year) // both returnng 1988
}
I'm not quite sure to understand the need for a static function as opposed to using a constructor!
package hwang.time
{
public class MyDate
{
private var _year:Number;
public function MyDate(year:Number)
{
_year = year;
}
public function get year():Number
{
return _year
}
}
}
//Then you can do...
TimeSpan.betweenMonths( new MyDate(1984), new MyDate(1988));