I have a json string that I need to map into a Model, I've been checking this json reader, Ext.data.reader.JsonView, but it seems that it only wokrs with a proxy, I need to pass a string (which contains the json) and map it to my model. Is that possible?
Thanks,
Angelo.
Take a look on the Ext.data.model's constructor.
http://docs.sencha.com/extjs/4.2.3/#!/api/Ext.data.Model-method-constructor
You can pass your data into it and it will map it to your model's fields. So you can do something like:
var model = new Ext.data.model(Ext.decode(<yourJsonString>));
Ext.data.model can be replaced with your model class.
Related
With dart / flutter it is possible to instantiate an Dart object from a jSON object.
For example, you define the dart class and instantiate an object of that class with the content from a jSON string via the API query.
The question is:
Is there any way that the jSON object contains additional variables that are then also available in the instantiated dart object? The goal is an ultra dynamic App, which is only supplied by the backend.
So far, I've been working with 'fixed' variable names or lists of subobjects.
This approach works perfectly smoothly.
I have not tried the approach of a dynamic variable from a jSON string yet.
I would like to ask if this is possible in principle before I design a concept based on this approach.
{
"widgetType": "radioGroup",
"label": "Level",
"integerValueNew": 200
}
#JsonSerializable()
class Input {
Input();
#JsonKey(required: true) String widgetType;
String label;
factory Input.fromJson(Map<String,dynamic> json) => _$InputFromJson(json);
Map<String, dynamic> toJson() => _$InputToJson(this);
}
In the Dart class only the variables 'widgetType' and 'label' are defined. Also the type of the variable is known, when an objekt is instantiated.
Can a dart object be instantiated from the shown jSON object, which then also contains the integer 'integerValueNew'?
If that works, you can develop a concept for it.
If not, I would work with sub-objects and well-defined variable names in Dart classes. Then the concept has to be broken down to a simple key value mapping.
I also do not know how the dart object should know which type of variable it is at all.
I want to save a JSON object as a Document in Couchbase. The id of this document is supposed to be retrieved from this JSON object and the value is supposed to be this JSON object itself. Since this JSON is too complex, I haven't mapped it directly to any POJO class, but I have created a Simple POJO, which has two fields as shown below
#Document
public class SimplePojo{
#Id
private String id;
#Field()
private String complexJsonString;//the JSON string is stored in this variable
}
I also have a SimplePojoRepository as shown below
#Component
public interface SimplePojoRepository extends CouchbaseRepository<SimplePojo, String>{
}
Now, I am setting the id and complexJsonString manually before calling the save method:-
SimplePojo myObj= new SimplePojo();
myObj.setId(myKey);
myObj.setComplexJsonString(jsonString);
simplePojoRepository.save(myObj);
This is working fine, but it is saving the Document in below format
myKey: {
complexJsonString : {//the original json Object here}
}
but I don't want this, I want to save it like this:-
myKey : {//the original json Object here}
So, to make it clear, I don't want to save my JSON object as a value of complexJsonString but rather, directly as a value of the myKey . Can someone please guide me on how to achieve this?
If you want to store the complexJsonString as a nested entity within your main object, you have to transform it in a Pojo:
myObj.setSomeEntity(new SomeEntity())
You can easily transform your JSON-encoded String to object using jackson's ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
mapper.readValue( jsonString, SomeEntity.class);
However, if you don't have control on the structure of this json, you will need to use the standard Java SDK instead of the Spring Data One:
JsonObject obj = JsonObject.create().put(this.documentTypeName, this.documentValue)
.put("attrNam1", "attrValue1")
.put("attrNam2", "attrValue2")
JsonDocument doc = JsonDocument.create(session.getId(), maxExpirationTime, obj);
bucket.upsert(doc)
In the case above, you will need to parse your JSON-encoded string using some lib (ex: gson/jackson) and then convert it to a couchbase JsonDocument.
Lastly, you could also leave your code as it is and use the N1QL function DECODE_JSON() whenever you need to access some property of this json string.
ex:
SELECT
i.itemName as itemName,
SUM(i.quantity) AS totalQuantity
FROM sessionstore s
UNNEST DECODE_JSON(s.sessionCart).shoppingCart.items i
WHERE s.sessionCart IS NOT MISSING
GROUP BY i.itemName
ORDER BY SUM(i.quantity) DESC
LIMIT 10
I have a project where I need to support serialising model classes to JSON using both Jackson and GSON (switchable).
Besides simply converting these model classes to JSON I also need to manipulate the by adding/removed certain keys (as per user input).
I was thinking of converting my model classes (and the logic to remove/add data) to simple java.util.Maps and convert these to JSON. Which works.
To convert these model classes to the java.util.Maps for Jackson I'm doing:
Map<String, Object> jsonMap =
mapper.convertValue(object, new TypeReference<Map<String, Object>() {})
and for GSON:
JsonElement jsonElement = gson.toJsonTree(object);
Map<String, Object> jsonMap =
gson.fromJson(jsonElement, new TypeToken<Map<String, Object>>(){}.getType());
After manipulating the data in the map, I do the following to actually serialize the map to JSON string:
// Jackson
mapper.writeValueAsString(jsonMap);
// GSON
gson.toJson(jsonMap);
Is there a performance hit to convert a model Object to a Map instead of a Jackson JsonNode (mapper.convertValue(object, ..) vs. mapper.valueToTree(object))?
Would it be possible to directly convert a model Object to a Map using GSON? Now I'm first creating a JsonElement and then converting it to a Map.
Jackson's ObjectNode uses LinkedHashMap internally (and ArrayNode uses ArrayList), so there should not be much difference between these approaches. JsonNode model can optimize some things slightly better than "raw" Lists and Maps; but on the other hand there is thin wrapper that adds some memory usage... so in the end things probably even out.
Is it possible to configure jackson to always add the type of the serialized object to the generated json output.
For example:
package org.acme;
class ClassA
{
String a;
String b;
}
and I want the generated json to be:
["org.acme.ClassA",{"a":"str1","b":"str2"}]
You can do that with enableDefaultTyping() of the ObjectMapper
e.g.
mapper.enableDefaultTyping(DefaultTyping.OBJECT_AND_NON_CONCRETE);
See ObjectMapper API
If your are free to change from Jackson and do not especially need the format to match the one your are showing you can try Genson http://code.google.com/p/genson.
For example if your requirement is to be able to deserialize interfaces or abstract classes based on the original type of the object you serialized you can do:
interface Entity {}
static class Person implements Entity {}
Genson genson = new Genson.Builder().setWithClassMetadata(true).create();
// json will be equal to {"#class":"my.package.Person"}
String json = genson.serialize(new Person());
// and now Genson is able to deserialize it back to Person using the information
// in the Json Object
Person person = (Person) genson.deserialize(json, Entity.class);
Another nice feature is the ability to define aliases for your classes, so you show less information in the json stream but also this allows you to do refactoring without worring of existing json streams (for example if you store it in a database).
Genson genson = new Genson.Builder().addAlias("person", Person.class).create();
// json value is {"#class": "person"}
String json = genson.serialize(new Person());
Have a look at the wiki.
We have used JSO for our JSON parsing in GWT client side. Now, we need to convert our Java objects to JSON string. I just wanted to understand, how we can achieve this? JSO overlay types was used for JSON parsing. Can it also be used to create a JSON request string or do we have to go by some other means?
Generating a JSON object in JavaScript is pretty simple. You can do it like this:
var obj = { "var1": "hello", "var2": "world" };
this will generate a JSON object with two varibles ("var1" and "var2") with their values ("hello", "world").
The Object can be converted into a String (for sending purposes) with the JSON.stringify(jso); method.
Generating JSON data from the java code isn't possible (well not with a usefull result) since all varibles are optimzed to single Strings, so applying this method wouldn't hava a usefull result (if even possible).
If you have already a JSO object (generated with something like safeeval). You can edit your varibles there, like this:
public final native void newValue(String newValue) /*-{
this.ValueName = newValue;
}-*/;
If you then want the object as string you have to define the following method in your JSO class:
public final native String returnAsString () /*-{
return JSON.stringify(this);
}-*/;
or use this in you Java class: String s = (new JSONObject(jso)).toString();.
This way you can edit your original intput data and send the original object back to the server.
BR