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.
Related
This is with the Docusign Rest api. When I call ToJson() on an EnvelopeDefinition, it returns the correct info, but I would like it to not serialize the base64 array for when I am writing this out to a log file. I tried using the [JsonIgnore] directive, but that stopped the array from being serialized altogether. Do I need to override the Serialize method on this class or just create another method, something like ToJsonForLogging() and not serialize that array?
I have created an extension method that will work for you. You can call this extension method in your code as follows
string json = envelopeDefinition.ToJsonLog(logDocumentBase64:false)
I am copying the DocumentBase64 into a temporary List and then using .ToJson() function to log without the documentBase64 property.
public static class EnvelopeDefinitionExtensions
{
public static string ToJsonLog(this EnvelopeDefinition envDefinition, bool logDocumentBase64 = true)
{
if (logDocumentBase64) return envDefinition.ToJson();
var tempDocumentBase64List = new List<string>();
foreach(var doc in envDefinition.Documents)
{
tempDocumentBase64List.Add(doc.DocumentBase64);
doc.DocumentBase64 = null;
}
string json = envDefinition.ToJson();
int i =0;
foreach(var doc in envDefinition.Documents)
{
doc.DocumentBase64 = tempDocumentBase64List[i];
i++;
}
return json;
}
}
I have a JSON which sends array of element in normal cases but sends empty string "" tag without array [] brackets in case of 0 elements.
How to handle this with Gson? I want to ignore the error and not cause JSONParsingException.
eg.
"types": [
"Environment",
"Management",
"Computers"
],
sometimes it returns:
"types" : ""
Getting the following exception: Expected BEGIN ARRAY but was string
Since you don't have control over the input JSON string, you can test the content and decide what to do with it.
Here is an example of a working Java class:
import com.google.gson.Gson;
import java.util.ArrayList;
public class Test {
class Types {
Object types;
}
public void test(String input) {
Gson gson = new Gson();
Types types = gson.fromJson(input,Types.class);
if(types.types instanceof ArrayList) {
System.out.println("types is an ArrayList");
} else if (types.types instanceof String) {
System.out.println("types is an empty String");
}
}
public static void main(String[] args) {
String input = "{\"types\": [\n" +
" \"Environment\",\n" +
" \"Management\",\n" +
" \"Computers\"\n" +
" ]}";
String input2 = "{\"types\" : \"\"}";
Test testing = new Test();
testing.test(input2); //change input2 to input
}
}
If a bad JSON schema is not under your control, you can implement a specific type adapter that would try to determine whether the given JSON document is fine for you and, if possible, make some transformations. I would recomment to use #JsonAdapter in order to specify improperly designed types (at least I hope the entire API is not improperly designed).
For example,
final class Wrapper {
#JsonAdapter(LenientListTypeAdapterFactory.class)
final List<String> types = null;
}
where LenientListTypeAdapterFactory can be implemented as follows:
final class LenientListTypeAdapterFactory
implements TypeAdapterFactory {
// Gson can instantiate it itself, let it just do it
private LenientListTypeAdapterFactory() {
}
#Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
// Obtaining the original list type adapter
#SuppressWarnings("unchecked")
final TypeAdapter<List<?>> realListTypeAdapter = (TypeAdapter<List<?>>) gson.getAdapter(typeToken);
// And wrap it up in the lenient JSON type adapter
#SuppressWarnings("unchecked")
final TypeAdapter<T> castTypeAdapter = (TypeAdapter<T>) new LenientListTypeAdapter(realListTypeAdapter);
return castTypeAdapter;
}
private static final class LenientListTypeAdapter
extends TypeAdapter<List<?>> {
private final TypeAdapter<List<?>> realListTypeAdapter;
private LenientListTypeAdapter(final TypeAdapter<List<?>> realListTypeAdapter) {
this.realListTypeAdapter = realListTypeAdapter;
}
#Override
public void write(final JsonWriter out, final List<?> value)
throws IOException {
realListTypeAdapter.write(out, value);
}
#Override
public List<?> read(final JsonReader in)
throws IOException {
// Check the next (effectively current) JSON token
switch ( in.peek() ) {
// If it's either `[...` or `null` -- we're supposing it's a "normal" list
case BEGIN_ARRAY:
case NULL:
return realListTypeAdapter.read(in);
// Is it a string?
case STRING:
// Skip the value entirely
in.skipValue();
// And return a new array list.
// Note that you might return emptyList() but Gson uses mutable lists so we do either
return new ArrayList<>();
// Not anything known else?
case END_ARRAY:
case BEGIN_OBJECT:
case END_OBJECT:
case NAME:
case NUMBER:
case BOOLEAN:
case END_DOCUMENT:
// Something definitely unexpected
throw new MalformedJsonException("Cannot parse " + in);
default:
// This would never happen unless Gson adds a new type token
throw new AssertionError();
}
}
}
}
Here is it how it can be tested:
for ( final String name : ImmutableList.of("3-elements.json", "0-elements.json") ) {
try ( final Reader reader = getPackageResourceReader(Q43562427.class, name) ) {
final Wrapper wrapper = gson.fromJson(reader, Wrapper.class);
System.out.println(wrapper.types);
}
}
Output:
[Environment, Management, Computers]
[]
If the entire API uses "" for empty arrays, then you can drop the #JsonAdapter annotation and register the LenientListTypeAdapterFactory via GsonBuilder, but add the following lines to the create method in order not to break other type adapters:
if ( !List.class.isAssignableFrom(typeToken.getRawType()) ) {
// This tells Gson to try to pick up the next best-match type adapter
return null;
}
...
There are a lot of weirdly designed JSON response choices, but this one hits the top #1 issue where nulls or empties are represented with "". Good luck!
Thanks for all your answers.
The recommed way as mentioned in above answers would be to use TypeAdapters and ExclusionStrategy for GSON.
Here is a good example Custom GSON desrialization
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.
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");
recently I have set up a WCF restful service with EF4.
It all worked out when returning XML format response. however when it comes to JSON, I got 504 Error. unable to return json data, WCF Resful Service .NET 4.0
By digging deeper by using Service Trace Viewer:
I found this error:
'The type 'xxx.DataEntity.AppView'
cannot be serialized to JSON because
its IsReference setting is 'True'. The
JSON format does not support
references because there is no
standardized format for representing
references. To enable serialization,
disable the IsReference setting on the
type or an appropriate parent class of
the type.'
The "AppView" is a complex object class which generated by EF4 from a store procedure.
I spend quite a bit time google how to disable the IsReference, very little result so far.
anyone? with any solutions?
thanks in advance
Code:
[OperationContract]
[WebInvoke(Method = "GET",
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "App/{id}/{format}")]
AppView FuncDetail(string id, string format);
public AppView FuncDetail(string id, string format)
{
SetResponseFormat(format);
return AppSvcs.GetById(id);
}
private void SetResponseFormat(string format)
{
if (format.ToLower() == "json")
{
ResponseContext.Format = WebMessageFormat.Json;
}
else
{
ResponseContext.Format = WebMessageFormat.Xml;
}
}
I ran into exactly the same issue. It only happened on one of my service methods where I was trying to return JSON serialised Entity objects. For all my other methods I was returning JSON serialised data transfer objects (DTOs), which are stand-alone and not connected to the Entity framework. I am using DTOs for data posted into methods. Often, the data you send out does not need all the data you store in the model or the database e.g. ID values, updated dates, etc. The mapping is done in the model class, like so:
public partial class Location
{
public static LocationDto CreateLocationDto(Location location)
{
LocationDto dto = new LocationDto
{
Accuracy = location.Accuracy,
Altitude = location.Altitude,
Bearing = location.Bearing
};
return dto;
}
It may seem a bit clunky but it works and it ensures that you only send the data fields you intended to send back. It works for me because I only have 5 or 6 entities but I can see that it would get a bit tedious if you have lots of classes.
I was running into the same problem, as caused by using the auto-generated ADO Entity Models. I have not found a direct fix for this issue, but as a work around, I serialize the response as json explicitly.
So in your example, the AppView FuncDetail looks like this:
public object FuncDetail(string id, string format)
{
SetResponseFormat(format);
// where AppSvc is the object type and the enumerable list of this type is returned by the GetById method, cast it to a json string
return JSONSerializer.ToJson<AppSvc>(AppSvcs.GetById(id));
}
Here are the Serializers that I'm using:
public static class GenericSerializer
{
public static DataTable ToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
}
public static class JSONSerializer
{
public static string ToJson<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = GenericSerializer.ToDataTable(varlist);
return GetJSONString(dtReturn);
}
static object RowsToDictionary(this DataTable table)
{
var columns = table.Columns.Cast<DataColumn>().ToArray();
return table.Rows.Cast<DataRow>().Select(r => columns.ToDictionary(c => c.ColumnName, c => r[c]));
}
static Dictionary<string, object> ToDictionary(this DataTable table)
{
return new Dictionary<string, object>
{
{ table.TableName, table.RowsToDictionary() }
};
}
static Dictionary<string, object> ToDictionary(this DataSet data)
{
return data.Tables.Cast<DataTable>().ToDictionary(t => "Table", t => t.RowsToDictionary());
}
public static string GetJSONString(DataTable table)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(table.ToDictionary());
}
public static string GetJSONString(DataSet data)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(data.ToDictionary());
}}
It is a lot clearer to use Entity Metadata instead of Reflection.
The Metadata is pretty extensive.
another way to do this is to use LINQ to create an anonymous type with the subset of fields that you need from your entity and then use JSON.NET to serialize the collection of anon types that you created in the LINQ statement. then persist that collection out as a string by serializing.