I receive from server a response in this form
{"error":null,"id":1,"result":{"admin":false,"firstname":"Jason","id":346,"idHotel":109,"idVendor":null,"lastname":"Butcher","sessionkey":"3c8a17ae47a6d131b1a14b44a1d8f9a9","urlAvatar":"avatar_316_mjm.jpg","urlThumb":"thumb_316_mjm.jpg"}}
And want to get the various singles attributes, in the nested json result as primitive
for example
Boolean error=..;
String admin=....;
String idHotel=...;
I have tried to make a class in this way
public class HotelLogin {
public boolean error;
public int id;
public Result result;
//get and set
public static class Result {
public String lastname;
...
...//get and set
}
}
and I have used this code tying to deserialize the JSONObject serverResponse
HotelLogin loggedRs= new HotelLogin();
Gson gson = new Gson();
response = gson.fromJson(serverResponse, HotelLogin.class);
But at this point I don't know how to get the single attributes of the inner json.
And if I use the code
Result user=login.getResult();
String lastname=user.getLastname();
Get a null pointer exception
Well, assuming that you have a variable or a return data which contains your server response, you can try this:
var newError = data.Error;
var newId = data.Id;
var newFirstName = data.result.firstname;
OR
var serverResponse = data; //(considering that this 'data' is your json object);
//you access it through dot notation.
serverResponse.error;
serverResponse.result.admin;
serverResponse.result.id;
Each one will get your required data. You can loop through your json object, if your prefer, but i like to use dot notation. Note that you can't always use it, since you must know if a attribute has a child node.
Related
Right now I am using Gson to deserialize JSON to Object.
The JSON looks like this:
[
{
"hash":"c8b2ce0aacede58da5d2b82225efb3b7",
"instanceid":"aa49882f-4534-4add-998c-09af078595d1",
"text":"{\"C_FirstName\":\"\",\"ContactID\":\"2776967\",\"C_LastName\":\"\"}",
"queueDate":"2016-06-28T01:03:36"
}
]
And my entity object looks like this:
public class AppCldFrmContact {
public String hash;
public String instanceid;
public HashMap<String,String> text;
public String queueDate;
}
If text was a String data type, everything would be fine. But then I wouldn't be able to access different fields as I want to.
Is there a way to convert given JSON to Object I want?
The error I am getting is: Expected BEGIN_OBJECT but was STRING at line 1 column 174, which is understandable if it cannot parse it.
The code doing the parsing:
Type listType = new TypeToken<List<AppCldFrmContact>>() {
}.getType();
List<AppCldFrmContact> contacts = gson.fromJson(response.body, listType);
For you expected result, JSON data should be like below format,
[
{
"hash":"c8b2ce0aacede58da5d2b82225efb3b7",
"instanceid":"aa49882f-4534-4add-998c-09af078595d1",
"text":{"C_FirstName":"","ContactID":"2776967","C_LastName":""},
"queueDate":"2016-06-28T01:03:36"
}
]
You are getting this error because text field is a JSON map serialized to the string. If it is an actual your data and not a just an example, you can annotate a field with #JsonDeserialize and write your own custom JsonDeserializer<HashMap<String,String>> which will make deserialization 2 times.
I am trying to parse the JSON from this link: https://api.guildwars2.com/v2/items/56 , everything fine until i met the line: "infix_upgrade":{"attributes":[{"attribute":"Power","modifier":4},{"attribute":"Precision","modifier":3}]} ...
If i dont get this wrong: infix_upgradehas 1 element attributes inside him. attributes has 2 elements with 2 other inside them. Is this a 2 dimension array?
I have tried (code too long to post):
JsonObject _detailsObject = _rootObject.get("details").getAsJsonObject();
JsonObject infix_upgradeObject = _detailsObject.get("infix_upgrade").getAsJsonObject();
JsonElement _infix_upgrade_attributesElement = infix_upgradeObject.get("attributes");
JsonArray _infix_upgrade_attributesJsonArray = _infix_upgrade_attributesElement.getAsJsonArray();
The problem is that I dont know what to do next, also tried to continue transforming JsonArray into string array like this:
Type _listType = new TypeToken<List<String>>() {}.getType();
List<String> _details_infusion_slotsStringArray = new Gson().fromJson(_infix_upgrade_attributesJsonArray, _listType);
but im getting java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT which i guess comes from the attributes...
With a proper formatting (JSONLint, for example, checks if the JSON data is valid and does the formatting, which makes the structure more clear than what the GW link gives), attributes looks actually like this:
"attributes": [
{
"attribute": "Power",
"modifier": 4
},
{
"attribute": "Precision",
"modifier": 3
}
]
So it's an array of JsonObject and each object as two key-value pairs. This is why the parser throws an error because you require that this array contains only String which is not the case.
So the actual type is:
Type _listType = new TypeToken<List<JsonObject>>(){}.getType();
The problem is that I dont know what to do next
Hold on. You are using Gson and Java is an OO language so I suggest you to create classes.
This would be easier for you to fetch the datas afterward and for the parsing since you just need to provide the class of the actual class the JSON data represents to the parser (some edge-cases could be handled by writing a custom serializer/deserializer).
The data is also better typed than this bunch of JsonObject/JsonArray/etc.
This will give you a good starting point:
class Equipment {
private String name;
private String description;
...
#SerializedName("game_types")
private List<String> gameTypes;
...
private Details details;
...
}
class Details {
...
#SerializedName("infix_upgrade")
private InfixUpgrade infixUpgrade;
...
}
class InfixUpgrade {
private List<Attribute> attributes;
...
}
class Attribute {
private String attribute;
private int modifier;
...
}
and then just give the type to the parser:
Equipment equipment = new Gson().fromJson(jsonString, Equipment.class);
Hope it helps! :)
I have json string represenatation of some object
class objects is
public class SMPBBaseObjectsList {
public ArrayList<Object> data = new ArrayList<>();
public Integer count;
public Integer limitFrom;
public Integer limitTo;
public Boolean hasMore;
public String dataItemsClass;
}
And i have json
{"classItem":"smpb.utility.classes.SMPBBaseObjectsList","dataItemsClass":"smpb.base.classes.SMPBUser","dataSliceCode":"012013","data":[{"id":1374046117510970000,"Name":"Test3","classItem":"smpb.base.classes.SMPBUser","dataSliceCode":"012013"}],"filter":{"orderItems":[],"filterItems":[]}}
I try parse this json and create object of my class with next code:
String json = "{\"classItem\":\"smpb.utility.classes.SMPBBaseObjectsList\",\"dataItemsClass\":\"smpb.base.classes.SMPBUser\",\"dataSliceCode\":\"012013\",\"data\":[{\"id\":1374046117510970000,\"Name\":\"Test3\",\"classItem\":\"smpb.base.classes.SMPBUser\",\"dataSliceCode\":\"012013\"}],\"filter\":{\"orderItems\":[],\"filterItems\":[]}}";
SMPBBaseObjectsList list = new GsonBuilder().create().fromJson(json, SMPBBaseObjectsList.class);
System.out.println("BEFORE:" + json);
System.out.println("AFTER: " + list);
System outputs:
BEFORE:{"classItem":"smpb.utility.classes.SMPBBaseObjectsList","dataItemsClass":"smpb.base.classes.SMPBUser","dataSliceCode":"012013","data":[{"id":1374044905885298000,"Name":"Test3","classItem":"smpb.base.classes.SMPBUser","dataSliceCode":"012013"}],"filter":{"orderItems":[],"filterItems":[]}}
AFTER: {"classItem":"smpb.utility.classes.SMPBBaseObjectsList","dataItemsClass":"smpb.base.classes.SMPBUser","dataSliceCode":"012013","data":[{"Name":"Test3","id":1.374044905885298011E18,"classItem":"smpb.base.classes.SMPBUser","dataSliceCode":"012013"}],"filter":{"orderItems":[],"filterItems":[]}}
As u can see in Json String i have ID with value 1374044905885298000 , but when object serialized from string i got 1.374044905885298011E18
And problem is what this representation of Long lost last zeros 0000 and i got Long 1374044905885297920
Why? and how fix it?
Data in Array is String map, and it's already all Long id Double format.
I try registerAdapater for Long or Double but never triggered.
Version of Gson 2.2.4
UPDATE
It's not duplicate of question
How to prevent Gson from converting a long number (a json string ) to scientific notation format?
I can't tell exactly what the problem is, but you can solve it by creating another class, i.e. Data to use in the List instead of the Object class... I tried this code and it's working fine for me!
So, you need to replace the ArrayList<Object> in your SMPBBaseObjectsList by:
public ArrayList<Data> data = new ArrayList<>()
And create a new class like this:
public class Data {
public Long id;
public String Name;
public String classItem;
public String dataSliceCode;
}
I guess there's an issue when parsing the JSON to an Object object, it probably makes some conversion that leads to that number formatting, but unfortunately I'm not an expert in this Java low-level issues...
Anyway, with this code you are explicitly specifying that you want that value parsed into a Long, so there's no problem!
I'm using a webservice which unfortunately I don't have any control over, there is one element called price that can have 2 types of values, it can either be a double:
price: 263.12
or a string with a specific format:
price: "263.12;Y"
In the second case the ;N indicates that the price can be modified (ie: a discount can be added), I tried to convince the developers of the service to modify the response and send the Y or N (depending on the case) in a separate value (discount: "Y" | "N:), but they said that for now they won't do it.
Within the POJO I declared for this case, I have the following case:
private float precio;
public void setPrice(String value){
if(value.indexOf(";") == -1){
price = Float.parseFloat(value);
} else {
String[] p = value.split(";");
price = Float.parseFloat(p[0]);
}
}
public float getPrice(){return price;}
But unfortunately using:
Product obj = new Gson().fromJson(response, Product.class);
Never actually cals the setter, in the cases where the price is set as a proper double it works just fine, but where I'm receiving the string it just crashes, any suggestions on how this could be handled, worst case scenario I could create a second POJO and try/catch the object creation, but there should be a better idea and searching so far has yielded no results.
You could implement a TypeAdapter that overwrites the default serialization. You have to register that TypeAdapter for a certain class ...
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Product.class, new ProductAdapter());
Gson gson = builder.create();
... so this way any members of type Product ...
String jsonString = gson.toJson(somethingThatContainsProducts);
... will be handled by the TypeAdapter:
public class ProductAdapter extends TypeAdapter<Product> {
public Product read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
String json = reader.nextString();
// convert String to product ... assuming Product has a
// constructor that creates an instance from a String
return new Product(json);
}
public void write(JsonWriter writer, Product value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
// convert Product to String .... assuming Product has a method getAsString()
String json = value.getAsString();
writer.value(json);
}
}
Check out the Google GSON documentation for more.
Hope this helps ... Cheers!
You could write a TypeAdapter or JsonDeserializer.
You can also just rely on the fact that Gson will massage types for you and go the other way with your type:
class Pojo { String price; }
...
String json = "{\"price\":1234.5}";
Pojo p = new Gson().fromJson(json, Pojo.class);
System.out.println(p.price);
produces:
1234.5
When you want to access/get price as a double , convert it appropriately in the getter.
I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?:
[
{
"user":{"id":"1","username":"user1"},
"item_name":"item1",
"custom_field":"custom1"
},
{
"user":{"id":"2","username":"user2"},
"item_name":"item2",
"custom_field":"custom2"
},
{
"user":{"id":"3","username":"user3"},
"item_name":"item3",
"custom_field":"custom3"
}
]
If you want to use Gson, then first you declare classes for holding each element and sub elements:
public class MyUser {
public String id;
public String username;
}
public class MyElement {
public MyUser user;
public String item_name;
public String custom_field;
}
Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it:
MyElement[] data = gson.fromJson (myJSONString, MyElement[].class);
Then you simply access the elements of data.
The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. e.g. "id", "item_name" etc.
If your trying to serialize/deserialize json in Java I would recommend using Jackson. http://jackson.codehaus.org/
Once you have Jackson downloaded you can deserialize the json strings to an object which matches the objects in JSON.
Jackson provides annotations that can be attached to your class which make deserialization pretty simple.
You could try JSON Simple
http://code.google.com/p/json-simple/
Example:
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonDataString);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject obj = (JSONObject) jsonArray.get(i);
//Access data with obj.get("item_name")
}
Just be careful to check for nulls/be careful with casting and such.