I already have some API and cannot change any parameters and object names into.
One of them is it:
{
"version":"1.0",
"error_code":"0",
"error_message":"OK",
"session_id":"2f0513adszdab61a4748553c62019a",
"expire":"2014-12-13 17:38:13",
"currencyData":{
"rate":"1",
"position":"1",
"ch":"dollar"
},
"data":{
"user_id":129733,
"account_type":0
},
"new":{
"messages_count":0,
"purchases_count":0,
"sales_count":0,
"offers_count":0,
"orders_count":0,
"cart_count":9
}
}
In this responce i have objects "currencyData", "data" and "new".
Right now i have troubles with this names after Deserialization, they are null.
My code for getting this recult is:
ApiResponse<UserData> response = new Gson().fromJson(json, UserData.class);
And names for target objects is:
private CurrencyData currencyData;
private UserData data;
private New newz;
Somebody can tell me how i can Deserialize this objects?
try this
private CurrencyData currencyData;
private UserData data;
#SerializedName("new")
private New newz;
Related
stucked at accessing nested json. similar stuff:
[
{
key-value,
key-value
},
{
key-value,
key-value
},
{
key-value,
key-value
}
]
works nicely but when i try:
{
"alfa":{
"id":"foo",
"product":{
"id":"foo1",
"price":"foo2"
}
},
"beta":{
"id":"foo",
"product":{
"id":"foo1",
"price":"foo2"
}
}
}
i get error:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<...
i of course did change structure of classes:
public class Alphabet{
private Purchase purchase;
...
public class Purchase{
private String id;
private Product product;
...
public class Product {
private String id;
private String price;
...
to read it:
ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = new FileInputStream(new File("src/main/json/file.json"));
TypeReference<List<Alphabet>> typeReference = new TypeReference<List<Alphabet>>() {};
List<Alphabet> alphabet= mapper.readValue(inputStream, typeReference);
System.out.println(alphabet);
whats wrong, please?
It seems like the JSON structure you try to read is not a List<Alphabet>, but a Map<String, Purchase>.
Your second json not like list of object. The second json look lik have 2 main objects if so you need class like below.
public class Alphabet{
private Purchase purchase;
private Purchase purchase1;
}
But it not good practice. Use as first josn like list of objects.
I'm trying to get a specific collection from a large json file but i don't want to make all the object structure on the json file because i only need the "calls" and "puts" fields...
the jsonfile is this: https://query2.finance.yahoo.com/v7/finance/options/AEIS?formatted=true&lang=en-US®ion=US&corsDomain=finance.yahoo.com
this is my class options... not posting getters and setters..
public class Option {
public enum Type { PUT, CALL }
#JsonIgnore
public Type type;
#JsonProperty("contractSymbol")
private String contractSymbol;
#JsonProperty("contractSize")
private String contractSize;
#JsonProperty("currency")
private String currency;
#JsonProperty("inTheMoney")
private boolean inTheMoney;
#JsonProperty("percentChange")
private Field percentChange;
#JsonProperty("strike")
private Field strike;
#JsonProperty("change")
private Field change;
#JsonProperty("impliedVolatility")
private Field impliedVolatility;
#JsonProperty("ask")
private Field ask;
#JsonProperty("bid")
private Field bid;
#JsonProperty("lastPrice")
private Field lastPrice;
#JsonProperty("volume")
private LongFormatField volume;
#JsonProperty("lastTradeDate")
private LongFormatField lastTradeDate;
#JsonProperty("expiration")
private LongFormatField expiration;
#JsonProperty("openInterest")
private LongFormatField openInterest;
}
and i'm trying to get data like this...
List<Option> res = JSON_MAPPER.readValue(new URL(link), new TypeReference<List<Option>>() {});
for(Option o: res){
o.type = Option.Type.CALL;
System.out.println(o.toString());
}
Aaand this is the exception...
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: https://query2.finance.yahoo.com/v7/finance/options/AEIS?formatted=true&lang=en-US®ion=US&corsDomain=finance.yahoo.com; line: 1, column: 16] (through reference chain: java.util.HashMap["optionChain"])
The problem is that the json return from the source begins with a object property, "optionChain", which Jackson try to deserialize it as HashMap, but you expect a List after deserialized.
As you mentioned you only need the "calls" and "puts" in the json, you can use ObjectMapper.readTree to get the whole JsonNode first, then find the node of "calls" by JsonNode.findValue, and finally deserialize the node. Following is an example:
String link = "https://query2.finance.yahoo" +
".com/v7/finance/options/AEIS?formatted=true&lang=en-US®ion=US&corsDomain=finance.yahoo.com";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(new URL(link));
JsonNode calls = jsonNode.findValue("calls");
List<Option> callOptions = mapper.readValue(calls.traverse(), new TypeReference<List<Option>>() {});
I have a JSON object stored in db in the form of string. I am using it to create dynamic form in the UI. Now the problem is I want to change some values in it based on other changes happening on the application. So suppose I updated label for the field, then I have to get this JSON and change that here.
This would be easy If I have stored same type of objects in this json, but my JSON is like follows:
[{
"name": "someName",
"xtype": "keyvaluecombo",
"fieldLabel": "Some Title",
"refType": "YES_NO",
"multiSelect": false,
"helpText": ""
},
{
"name": "someName2",
"xtype": "keyvaluecombo",
"fieldLabel": "Some Title2",
"refType": "YES_NO",
"multiSelect": false,
"helpText": ""
},
{
"xtype": "datefield",
"fieldLabel": "Joining Date",
"name": "joiningDate",
"submitFormat": "Y-m-d"
},
{
"xtype": "userselectioncombo",
"fieldLabel": "Selection",
"name": "selections",
"filterBy": {
"functions": [
"select"
]
}
}]
Now this is stored as String in db, what is efficient way of changing fieldLabel based on name. I could have tried working on it as string only and use regular expression, but that didn't feel right.
You should write a bean class, which should be mapping to you Json object like,
public class abc {
private String name;
private String xtype;
private String fieldLabel;
........
}
Then you should use
import java.lang.reflect.Type;
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Type type = new TypeToken<List<abc>>() {
}.getType();
List<abc> abcList = gson.fromJson(confTemplate,
type); // confTemplate is your Json object you get from DB
this will get the list of beans.
for (abc abcData : abcList ) {
// you can do your stuff
}
First of all the best way, changing your database design with a new one that suits your model. Not keeping json in your database as a column. But if you can't do that, because sometimes it's impossible to change old db designs you can trace the following way.
And of course you should read your json from db before start and save it again after the below process.
Create a custom object that suits your model.
public class MyObject{
private String name;
private String fieldLabel;
public String getFieldLabel(){
return fieldLabel;
}
public void setFieldLabel( String fieldLabel ){
this.fieldLabel = fieldLabel;
}
public String getName(){
return name;
}
public void setName( String name ){
this.name = name;
}
// bla bla other fields
Convert your json into your object, and vice versa see the code example below:
public static void main( String[] args ){
Gson gson = new Gson();
String yourJson = "[{'name':'someName','xtype':'keyvaluecombo','fieldLabel':'Some Title','refType':'YES_NO','multiSelect':false,'helpText':''},{'name':'someName2','xtype':'keyvaluecombo','fieldLabel':'Some Title2','refType':'YES_NO','multiSelect':false,'helpText':''},{'xtype':'datefield','fieldLabel':'Joining Date','name':'joiningDate','submitFormat':'Y-m-d'},{'xtype':'userselectioncombo','fieldLabel':'Selection','name':'selections','filterBy':{'functions':['select']}}]";
// changing single quotes with double ones.
yourJson = yourJson.replaceAll( "'", "\"" );
JsonArray jsonArray = new JsonParser().parse( yourJson ).getAsJsonArray();
List<MyObject> result = new ArrayList<MyObject>();
for( JsonElement jsonElement : jsonArray ){
MyObject myObject = gson.fromJson( jsonElement, MyObject.class );
// change fields as you wish
if( myObject.getName().equals( "someName" ) ){
myObject.setFieldLabel( "TEST" );
}
// add it to another list
result.add( myObject );
}
// convert into another json again..
System.out.println( gson.toJson( result ) );
}
Easy to realize that Object in your list have attributes below:
"name"
"xtype"
"fieldLabel"
"refType"
"multiSelect"
"helpText"
"submitFormat"
"filterBy"
So you can create an Object which has over attributes. Using ObjectMapper for deserialize the list:
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, new TypeReference<ArrayList<T>>() {})
After have a list object you can loop for change any attribute or change attribute of an specific item you want.
I want to use Gson to Deserialize my JSON into objects.
I've defined the appropriate classes, and some of those class' objects are included in other objects.
When trying to deserialize the whole JSON, I got null values, so I started breaking it apart.
I reached the point where all lower classes stand by them selves, but when trying to deserialize into an object that holds an instance of that smaller object - every thing returns as null.
My partial JSON:
{
"user_profile": {
"pk": 1,
"model": "vcb.userprofile",
"fields": {
"photo": "images/users/Screen_Shot_2013-03-18_at_5.24.13_PM.png",
"facebook_url": "https://google.com/facebook",
"site_name": "simple food",
"user": {
"pk": 1,
"model": "auth.user",
"fields": {
"first_name": "blue",
"last_name": "bla"
}
},
"site_url": "https://google.com/"
}
}
}
UserProfile Class:
public class UserProfile {
private int pk;
private String model;
private UPfields fields = new UPfields();//i tried with and without the "new"
}
UPfields Class:
public class UPfields {
private String photo;
private String facebook_url;
private String site_name;
private User user;
private String site_url;
}
User Class:
public class User {
private int pk;
private String model;
private Ufields fields;
}
Ufields Class:
public class Ufields {
private String first_name;
private String last_name;
}
In my main I call:
Gson gson = new Gson();
UserProfile temp = gson.fromJson(json, UserProfile.class);
So my temp object contain only null values.
I've tried changing the classes to static, and it doesn't work.
The UPfields object and all lower one work fine.
Any suggestions?
when I remove the
"{
"user_profile":"
and it's closing bracket, the deserialize to a user_profile object works.
In order to parse this json example you have to create auxiliary class, which will contain field named user_profile of type UserProfile:
public class UserProfileWrapper {
private UserProfile user_profile;
}
and parse this json string with this class:
UserProfileWrapper temp = gson.fromJson(json, UserProfileWrapper.class);
Gson starts by parsing the outermost object, which in your case has a single field, user_profile. Your UserProfile class doesn't have a user_profile field, so it can't deserialize it as an instance of that class. You should try to deserialize the value of the user_profile field instead.
I am trying to parse a JSON response. I am getting JSON response like below:
"libraryLastModified" : "2012-10-10 03:57:26",
"playlists" : { "10063" : { "id" : "10063",
"name" : "Favorites",
"songs" : [ "10006134",
"10006053",
"10006274",
"10006167",
]
},
"10157" : { "id" : "10157",
"name" : "80s",
"songs" : [ "10006694",
"10006695",
"10006697",
"10006699",
"10006698",
]
}
How can I access the id & name values?
I love GSON. In this scenario you'd create two classes.
public class PLayList {
private int id;
private String name;
private List<Integer> songs;
//getters and setters
}
public class Library {
private Date libraryLastModified;
private List<Playlist> playlists;
//getters and setters
}
Then you can write
Gson gson = new Gson();
Library result = gson.fromJson(theInput, Library.class);
Since the playlists is coming to you as key:value you'd need to write a custom deserializer for them. Taje a look at GSON deserializing key-value to custom object for how to do that
In pseudocode. I don't remember exactly the JSON methods
JSONObject mainObj = parseJson
JSONObject playLists = mainObj.getJSONObject("playlists")
JSONObject myList = playList.getJSONObject("10063")
id = myList.getString("id")
To iterate over several lists, you'd better transform playlists to a JSONArray, then you can iterate over it. If you can't do that, check the Android JSON API and check how to get all keys for a JSONObject and then iterate over the keys
for(int i=0;i<playlistKeys.length;i++){
playlistObj = playLists.getJSONObject(playlistsKey[i])
}
use google Gson.
http://code.google.com/p/google-gson/
class Response{
Date libraryLastModified;
Playlist []playlists;
class Playlist{
Long id;
String name;
Long[] songs;
}
}
String _response=... //Your response from web
Response response = new GsonBuilder().setDateFormat("yyyy-MM-dd' 'HH:mm:ss").create().fromJson(_response, Response.class);
String songName = response.playlists[0].name;