Unity3D: How to access List<T> elements from ParseObject subclass - json

I cannot seem to access an array of custom objects (that is a column in a Parse table) after querying for it and receiving the results.
I have a simple custom class call "TextEntry" that contains 2 strings.
public class TextEntry
{
public string key;
public string text;
public TextEntry() { }
}
I have a ParseObject subclass called "LocalePO", which has an IList member in addition to other native types.
[ParseClassName("LocalePO")]
public class LocalePO : ParseObject
{
[ParseFieldName("version")]
public int version
{
get { return GetProperty<int>("version"); }
set { SetProperty<int>(value, "version"); }
}
[ParseFieldName("code")]
public string code
{
get { return GetProperty<string>("code"); }
set { SetProperty<string>(value, "code"); }
}
[ParseFieldName("name")]
public string name
{
get { return GetProperty<string>("name"); }
set { SetProperty<string>(value, "name"); }
}
[ParseFieldName("keypair")]
public IList<object> keypair
{
get { return GetProperty<IList<object>>("keypair"); }
set { SetProperty<IList<object>>(value, "keypair"); }
}
public LocalePO() { }
}
I can query to Parse and successfully return a LocalePO object, but I cannot access the specific "TextEntry" members of the "keypair" List afterwards.
var cloudQuery = new ParseQuery<LocalePO>();
var queryTask = cloudQuery.FirstAsync();
// wait for query to return
while (!queryTask.IsCompleted) yield return null;
LocalePO locale = queryTask.Result;
int CloudVersion = locale.version; // this works
List<TextEntry> list = new List<TextEntry>();
list = locale.keypair.Cast<TextEntry>.ToList(); // this doesn't work
foreach (var item in locale.keypair)
{
var entry = item as TextEntry; // this does not work
TextEntry entry = (TextEntry)item; // this doesn't work either
// this is my current solution which works but seems terrible
string json = JsonConvert.SerializeObject(item);
TextEntry entry = JsonConvert.DeserializeObject<TextEntry>(json);
list.Add(entry);
}
I feel like I am overlooking something very simple here, but I just want to convert the data I pull from Parse to local objects so I can use the data throughout the app logic.
It seems to me that Parse prefers the IList of type "object"vs an IList of type "TextEntry" type for the ParseFieldName. For example, Parse always returns null for the field if I have the following:
[ParseFieldName("keypair")]
public IList<TextEntry> keypair
{
get { return GetProperty<IList<TextEntry>>("keypair"); }
set { SetProperty<IList<TextEntry>>(value, "keypair"); }
}
Perhaps I should derive TextEntry from ParseObject too? I'm so confused.
Any help would be appreciated.
Thanks!

Try this:
var cloudQuery = new ParseQuery<LocalePO>();
cloudQuery .Include("keypair");
var queryTask = cloudQuery.FirstAsync();
TextEntry will need to derive from parseObject and you will need to register it as a subclass.
Here is an example of a query I am using which has 2 levels of nested iList's of parseObject subclasses
ParseObject.RegisterSubclass<ProgramDataParse>();
ParseObject.RegisterSubclass<WorkoutDataParse>();
ParseObject.RegisterSubclass<ExerciseDataParse>();
var programQuery = new ParseQuery<ProgramDataParse>()
.OrderByDescending("createdAt").Limit(2)
.Include("workouts")
.Include("workouts.exercises");

Related

Mapping parsed json to java object not working-LibGdx

First time I am using json parsing in my LibGDX project and I am not able to get the parsed results properly.
Here I want to manage the obstacles with properties;name,direction,gap and speed.
I have a json file like this:
"obstacles": [
{"name":"eagle","dir":"up","gap":"100","speed":"0"},
{"name":"bigbird","dir":"up","gap":"200","speed":"0"},
{"name":"elephant","dir":"middle","gap":"300","speed":"0"},
{"name":"tiger","dir":"middle","gap":"400","speed":"0"},
{"name":"bear","dir":"down","gap":"500","speed":"0"},
],
and I am reading the array like this:
public class ReadJson {
static int levelNum = 0;
public ReadJson()
{
}
public static synchronized ArrayList<String> loadLevelJson(int levelno, String name) {
ArrayList obs = new ArrayList<String>();
JsonValue jsonValue = new JsonReader().parse(Gdx.files.internal("levels/level1.json"));
JsonValue objList = jsonValue.get(name);
System.out.println("name:" + objList);
if (name.equals("obstacles")) {
Constants.OBS_COUNT = 0;
for (JsonValue values : objList.iterator()) // iterator() returns a
// list of children
{
obs.add(values.getString("dir"));
Constants.OBS_POSITION[obs.size() - 1] = Integer.parseInt(values.getString("gap"));
Constants.OBS_NAME[obs.size() - 1] = values.getString("name");
Constants.OBS_SPEED[obs.size() - 1] = Integer.parseInt(values.getString("speed"));
Constants.OBS_COUNT++;
}
}
else if (.....)) {
//code
}
return obs;
}
}
Arrays are defined in constant class like this:
public static int OBS_COUNT =20;
public static int[] OBS_POSITION= new int[50];
public static String[] OBS_NAME= new String[50];
public static int[] OBS_SPEED= new int[50];
public static ArrayList<String> obsArray;
I want to map the parsed json to the object bear.For that,I did like this:
private ReadJson readJson;
public ObsObjectFactory() {
readJson = new ReadJson();
readJson.loadLevelJson(1,"obstacles");
Constants.obsArray=readJson.loadLevelJson(1,"obstacles");
}
public Bear createBear() {
Bear bear = new Bear();
bear.setName(Constants.OBS_NAME[Constants.OBS_COUNT]);
bear.setDirection(Constants.obsArray.get(Constants.OBS_COUNT));
bear.setSpeed(Constants.OBS_SPEED[Constants.OBS_COUNT]);
bear.setGap(Constants.OBS_POSITION[Constants.OBS_COUNT]);
bear.setPosition(Constants.EAGLE_X,Constants.EAGLE_Y);
bear.setSize(Constants.BEAR_WIDTH,Constants.BEAR_HEIGHT);
return bear;
}
}
But when I call this createBear()method and run this code,it is throwing IndexOutOfBoundsException in this line:
bear.setDirection(Constants.obsArray.get(Constants.OBS_COUNT));
Parsed values are displaying properly in console.
What mistake I did here?
Your constants don't seem to be constants, as they can change. I found that odd, and as another aside, the code is quite confusing to follow. I'm not entirely sure what you're trying to achieve.
But the index error is likely caused by incrementing your constant (hint, not a constant then, is it?) Constants.OBS_COUNT++; in the readJson method. Given your json file, OBS_COUNT might end up being 5, so Constants.obsArray.get(Constants.OBS_COUNT) is failing as your array only has index positions 0 through 4.

How to add an extra property into a serialized JSON string using json.net?

I am using Json.net in my MVC 4 program.
I have an object item of class Item.
I did:
string j = JsonConvert.SerializeObject(item);
Now I want to add an extra property, like "feeClass" : "A" into j.
How can I use Json.net to achieve this?
You have a few options.
The easiest way, as #Manvik suggested, is simply to add another property to your class and set its value prior to serializing.
If you don't want to do that, the next easiest way is to load your object into a JObject, append the new property value, then write out the JSON from there. Here is a simple example:
class Item
{
public int ID { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Item item = new Item { ID = 1234, Name = "FooBar" };
JObject jo = JObject.FromObject(item);
jo.Add("feeClass", "A");
string json = jo.ToString();
Console.WriteLine(json);
}
}
Here is the output of the above:
{
"ID": 1234,
"Name": "FooBar",
"feeClass": "A"
}
Another possibility is to create a custom JsonConverter for your Item class and use that during serialization. A JsonConverter allows you to have complete control over what gets written during the serialization process for a particular class. You can add properties, suppress properties, or even write out a different structure if you want. For this particular situation, I think it is probably overkill, but it is another option.
Following is the cleanest way I could implement this
dynamic obj = JsonConvert.DeserializeObject(jsonstring);
obj.NewProperty = "value";
var payload = JsonConvert.SerializeObject(obj);
You could use ExpandoObject.
Deserialize to that, add your property, and serialize back.
Pseudocode:
Expando obj = JsonConvert.Deserializeobject<Expando>(jsonstring);
obj.AddeProp = "somevalue";
string addedPropString = JsonConvert.Serializeobject(obj);
I think the most efficient way to serialize a property that doesn't exist in the type is to use a custom contract resolver. This avoids littering your class with the property you don't want, and also avoids the performance hit of the extra serialization round trip that most of the other options on this page incur.
public class SpecialItemContractResolver : DefaultContractResolver {
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) {
var list = base.CreateProperties(type, memberSerialization);
if (type.Equals(typeof(Item))) {
var feeClassProperty = CreateFeeClassProperty();
list.Add(feeClassProperty);
}
return list;
}
private JsonProperty CreateFeeClassProperty() {
return new JsonProperty {
PropertyName = "feeClass",
PropertyType = typeof(string),
DeclaringType = typeof(Item),
ValueProvider = new FeeClassValueProvider(),
AttributeProvider = null,
Readable = true,
Writable = false,
ShouldSerialize = _ => true
};
}
private class FeeClassValueProvider : IValueProvider {
public object GetValue(object target) => "A";
public void SetValue(object target, object value) { }
}
}
To use this functionality:
// This could be put in a static readonly place so it's reused
var serializerSettings = new JsonSerializerSettings {
ContractResolver = new SpecialItemContractResolver()
};
// And then to serialize:
var item = new Item();
var json = JsonConvert.Serialize(item, serializerSettings);

GXT 3.0 JsonReader with multiple root objects

I'm starting out with GXT and am a bit confused on how to use the JsonReader to parse a valid json string with multiple root objects. I have a set of selection boxes to build the sql statement to display records in a grid. I'm getting the values for the selections from the database as well. What I'm attempting to do is a single request to my php database functions to build the json with all the values for the selection boxes in one string. My first thought was the JsonReader.
Here's an example of the json I'm working with:
"categories":[{"id":"1","value":"categoryValue1"},{"id":"2","value":"categoryValue2"}], "frequencies":[{"id":"1","value":"frequencyValue1"},{"id":"2","value":"frequencyValue2"}]
Building off the cityList example in the api, this is what I've got so far.
JsonRootObject interface:
public interface JsonRootObject {
List<SelectionProperties> getCategories();
List<SelectionProperties> getFrequencies();
}
JsonRootObjectAutoBeanFactory:
public interface JsonRootObjectAutoBeanFactory extends AutoBeanFactory {
AutoBean<JsonRootObject> jsonRootObject();
}
I created a SelectionProperties interface as all are single int/string value pairs:
public interface SelectionProperties {
String getId();
String getValue();
}
Now, according to the api:
// To convert from JSON data, extend a JsonReader and override
// createReturnData to return the desired type.
So I created a reader for both categories and frequencies;
CategoryReader:
public class CategoryReader
extends
JsonReader<ListLoadResult<SelectionProperties>, JsonRootObject> {
public CategoriesReader(AutoBeanFactory factory, Class<JsonRootObject> rootBeanType) {
super(factory, rootBeanType);
}
protected ListLoadResult<SelectionProperties> createReturnData(Object loadConfig, JsonRootObject incomingData) {
return new ListLoadResultBean<SelectionProperties>(incomingData.getCategories());
}
}
FrequencyReader:
public class FrequencyReader extends
JsonReader<ListLoadResult<SelectionProperties>, net.apoplectic.testapps.client.JsonRootObject> {
public FrequencyReader(AutoBeanFactory factory, Class<JsonRootObject> rootBeanType) {
super(factory, rootBeanType);
}
protected ListLoadResult<SelectionProperties> createReturnData(Object loadConfig, JsonRootObject incomingData) {
return new ListLoadResultBean<SelectionProperties>(incomingData.getFrequencies());
}
}
This doesn't feel quite right. I'm creating multiple instances of basically the same code and parsing the actual json string twice (at this point. I may have more options for the grid once I dig in). My question is am I missing something or is there a more efficient way to parse the response string? From my onSuccessfulResponse:
JsonRootObjectAutoBeanFactory factory = GWT.create(JsonRootObjectAutoBeanFactory.class);
CategoryReader catReader = new CategoriesReader(factory, JsonRootObject.class);
FrequencyReader freqReader = new FrequenciesReader(factory, JsonRootObject.class);
categories = catReader.read(null, response);
frequencies = freqReader.read(null, response);
List<SelectionProperties> categoriesList = categories.getData();
List<SelectionProperties> frequenciesList = frequencies.getData();
ListBox cateBox = new ListBox(false);
ListBox freqBox = new ListBox(false);
for (SelectionProperties category : categoriesList )
{
cateBox.addItem(category.getValue(), category.getId());
}
for (SelectionProperties frequency : frequenciesList)
{
freqBox.addItem(frequency.getValue(), frequency.getId());
}
The above does work, both the ListBoxes are populated correctly. I just wonder if this is the correct approach. Thanks in advance!

Grails JSONBuilder

If I have a simple object such as
class Person {
String name
Integer age
}
I can easily render it's user-defined properties as JSON using the JSONBuilder
def person = new Person(name: 'bob', age: 22)
def builder = new JSONBuilder.build {
person.properties.each {propName, propValue ->
if (!['class', 'metaClass'].contains(propName)) {
// It seems "propName = propValue" doesn't work when propName is dynamic so we need to
// set the property on the builder using this syntax instead
setProperty(propName, propValue)
}
}
def json = builder.toString()
This works fine when the properties are simple, i.e. numbers or strings. However for a more complex object such as
class ComplexPerson {
Name name
Integer age
Address address
}
class Name {
String first
String second
}
class Address {
Integer houseNumber
String streetName
String country
}
Is there a way that I can walk the entire object graph, adding each user-defined property at the appropriate nesting level to the JSONBuilder?
In other words, for an instance of ComplexPerson I would like the output to be
{
name: {
first: 'john',
second: 'doe'
},
age: 20,
address: {
houseNumber: 123,
streetName: 'Evergreen Terrace',
country: 'Iraq'
}
}
Update
I don't think I can use the Grails JSON converter to do this because the actual JSON structure I'm returning looks something like
{ status: false,
message: "some message",
object: // JSON for person goes here
}
Notice that:
The JSON generated for the ComplexPerson is an element of a larger JSON object
I want to exclude certain properties such as metaClass and class from the JSON conversion
If it's possible to get the output of the JSON converter as an object, I could iterate over that and remove the metaClass and class properties, then add it to the outer JSON object.
However, as far as I can tell, the JSON converter only seems to offer an "all or nothing" approach and returns it output as a String
I finally figured out how to do this using a JSONBuilder, here's the code
import grails.web.*
class JSONSerializer {
def target
String getJSON() {
Closure jsonFormat = {
object = {
// Set the delegate of buildJSON to ensure that missing methods called thereby are routed to the JSONBuilder
buildJSON.delegate = delegate
buildJSON(target)
}
}
def json = new JSONBuilder().build(jsonFormat)
return json.toString(true)
}
private buildJSON = {obj ->
obj.properties.each {propName, propValue ->
if (!['class', 'metaClass'].contains(propName)) {
if (isSimple(propValue)) {
// It seems "propName = propValue" doesn't work when propName is dynamic so we need to
// set the property on the builder using this syntax instead
setProperty(propName, propValue)
} else {
// create a nested JSON object and recursively call this function to serialize it
Closure nestedObject = {
buildJSON(propValue)
}
setProperty(propName, nestedObject)
}
}
}
}
/**
* A simple object is one that can be set directly as the value of a JSON property, examples include strings,
* numbers, booleans, etc.
*
* #param propValue
* #return
*/
private boolean isSimple(propValue) {
// This is a bit simplistic as an object might very well be Serializable but have properties that we want
// to render in JSON as a nested object. If we run into this issue, replace the test below with an test
// for whether propValue is an instanceof Number, String, Boolean, Char, etc.
propValue instanceof Serializable || propValue == null
}
}
You can test this by pasting the code above along with the following into the grails console
// Define a class we'll use to test the builder
class Complex {
String name
def nest2 = new Expando(p1: 'val1', p2: 'val2')
def nest1 = new Expando(p1: 'val1', p2: 'val2')
}
// test the class
new JSONSerializer(target: new Complex()).getJSON()
It should generate the following output which stores the serialized instance of Complex as the value of the object property:
{"object": {
"nest2": {
"p2": "val2",
"p1": "val1"
},
"nest1": {
"p2": "val2",
"p1": "val1"
},
"name": null
}}
In order for the converter to convert the whole object structure you need to set a property in the config to indicate that, otherwise it will just include the ID of the child object, so you need to add this:
grails.converters.json.default.deep = true
For more information go Grails Converters Reference.
However, like you mentioned it in the comment above it is all or nothing, so what you can do is create your own marshaller for your class. I had to do this before because I needed to include some very specific properties, so what I did was that I created a class that extends org.codehaus.groovy.grails.web.converters.marshaller.json.DomainClassMarshaller. Something like:
class MyDomainClassJSONMarshaller extends DomainClassMarshaller {
public MyDomainClassJSONMarshaller() {
super(false)
}
#Override
public boolean supports(Object o) {
return (ConverterUtil.isDomainClass(o.getClass()) &&
(o instanceof MyDomain))
}
#Override
public void marshalObject(Object value, JSON json) throws ConverterException {
JSONWriter writer = json.getWriter();
Class clazz = value.getClass();
GrailsDomainClass domainClass = ConverterUtil.getDomainClass(clazz.getName());
BeanWrapper beanWrapper = new BeanWrapperImpl(value);
writer.object();
writer.key("class").value(domainClass.getClazz().getName());
GrailsDomainClassProperty id = domainClass.getIdentifier();
Object idValue = extractValue(value, id);
json.property("id", idValue);
GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();
for (GrailsDomainClassProperty property: properties) {
if (!DomainClassHelper.isTransient(transientProperties, property)) {
if (!property.isAssociation()) {
writer.key(property.getName());
// Write non-relation property
Object val = beanWrapper.getPropertyValue(property.getName());
json.convertAnother(val);
} else {
Object referenceObject = beanWrapper.getPropertyValue(property.getName());
if (referenceObject == null) {
writer.key(property.getName());
writer.value(null);
} else {
if (referenceObject instanceof AbstractPersistentCollection) {
if (isRenderDomainClassRelations(value)) {
writer.key(property.getName());
// Force initialisation and get a non-persistent Collection Type
AbstractPersistentCollection acol = (AbstractPersistentCollection) referenceObject;
acol.forceInitialization();
if (referenceObject instanceof SortedMap) {
referenceObject = new TreeMap((SortedMap) referenceObject);
} else if (referenceObject instanceof SortedSet) {
referenceObject = new TreeSet((SortedSet) referenceObject);
} else if (referenceObject instanceof Set) {
referenceObject = new HashSet((Set) referenceObject);
} else if (referenceObject instanceof Map) {
referenceObject = new HashMap((Map) referenceObject);
} else {
referenceObject = new ArrayList((Collection) referenceObject);
}
json.convertAnother(referenceObject);
}
} else {
writer.key(property.getName());
if (!Hibernate.isInitialized(referenceObject)) {
Hibernate.initialize(referenceObject);
}
json.convertAnother(referenceObject);
}
}
}
}
}
writer.endObject();
}
...
}
That code above is pretty much the same code as it is DomainClassMarshaller, the idea would be that you add or remove what you need.
Then in order for Grails to use this new converter what you need is to register it in the resources.groovy file, like this:
// Here we are regitering our own domain class JSON Marshaller for MyDomain class
myDomainClassJSONObjectMarshallerRegisterer(ObjectMarshallerRegisterer) {
converterClass = grails.converters.JSON.class
marshaller = {MyDomainClassJSONMarshaller myDomainClassJSONObjectMarshaller ->
// nothing to configure, just need the instance
}
priority = 10
}
As you can see this marshaller works for a specific class, so if you want to make more generic what you can do is create a super class and make your classes inherit from that so in the support method what you do is say this marshaller support all the classes that are instances of that super class.
My suggestion is to review the grails code for the converters, that will give you an idea of how they work internally and then how you can extend it so it works the way you need.
This other post in Nabble might be of help too.
Also, if you need to do it for XML as well then you just extend the class org.codehaus.groovy.grails.web.converters.marshaller.xml.DomainClassMarshaller and follow the same process to register it, etc.

How to determine lazy-loaded properties at runtime on a linq table?

I am iterating over the properties of various mapped tables in my code and need to know whether or not each property is lazy loaded. I have found that the instance variable used for storage, denoted by the Storage attribute on the property, will be of type System.Data.Linq.Link.
Is there a way that I can leverage these two facts at runtime to solve this problem?
Code:
public void LazyLoad(Type tableType)
{
foreach (var prop in tableType.GetGenericArguments()[0].GetProperties())
{
if (/* IS LAZY LOADED */)
{
//real work here...
Console.WriteLine(prop.Name);
}
}
}
The mappings look like this:
public partial class Address
{
private System.Data.Linq.Link<string> _City;
[Column(Storage="_City", DbType="...")]
public string City
{
get { /* ... */ }
set { /* ... */ }
}
}
You are almost there. Just a spoon full of reflection helps the medicine go down ;-)
private static bool IsLazyLoadedProperty(PropertyInfo property)
{
var column = property.GetCustomAttributes(typeof(ColumnAttribute), true)[0]
as ColumnAttribute;
var field = property.DeclaringType.GetField(column.Storage,
BindingFlags.Instance | BindingFlags.NonPublic);
if (!field.FieldType.IsGenericType)
{
return false;
}
return field.FieldType.GetGenericTypeDefinition() == typeof(Link<>);
}