How can I parse this json via Gson?
Here is my PodModel.class
And this is my for retrieve the json.
This is the gson part.
gson = new Gson();
PodsModel pods = gson.fromJson(builder.toString(), PodsModel.class);
System.out.println(pods.getPods().getDomain());
Logcat returns with this: logcat-output
It seems, that Gson failed here:
"pods":[{"id":
^
This [ is unexpected because in your model PodModel pods field is plain field, not an array.
May be you have to change pods to by an array, and in this case you will be able to parse such json.
UPD: Just change pods definition to this one:
private List<ItemPod> pods;
change according way getter and setter.
This solution should work (tested).
Related
What im trying to do is
JSON:
{
aKey:{
aChildKey:""
},
bKey:""
}
expected:
aKey:{
aChildKey:"aKey.aChildKey"
},
bKey:"bKey"
}
Please can some one help me in getting the expected the value
You need to deserialize the JSON into an object, set the values, then serialize it back into JSON. There are a number of libraries you can use for this, like org.json, gson, or Jackson. Those libraries also allow you to modify the value directly. For example, using org.json, you can do something like this:
JSONObject jsonObject = new JSONObject(myJsonString);
jsonObject.getJSONObject("akey").put("aChildKey","aKey.aChildKey");
See How to parse JSON in Java
There are many threads related to this, but I can't solve my issue.
I get this string from parsing an iterable using GSON.
Iterable<ParametrosProveedores> proveedoresList;
proveedoresList = proveedoresRepository.findAll(); //From spring repository
String jsonString = gson.toJson(proveedoresList);
jsonString value is:
[{\"id\":1,\"proveedor\":\"CALIXTA\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"todas\",\"plazasNo\":\"\",\"turnoUnaVia\":false,\"turnoDosVias\":false},{\"id\":2,\"proveedor\":\"MOVILE\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"51,52\",\"plazasNo\":\"\",\"turnoUnaVia\":false,\"turnoDosVias\":false},{\"id\":3,\"proveedor\":\"TWILIO\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"todas\",\"plazasNo\":\"51\",\"turnoUnaVia\":false,\"turnoDosVias\":false},{\"id\":4,\"proveedor\":\"OTRO\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"todas\",\"plazasNo\":\"\",\"turnoUnaVia\":false,\"turnoDosVias\":false}]
Which is a json array. Is there really no way to parse from that string without removing escapes manually?
All I want to do is:
JSONArray jsonArray = parseFrom(jsonString);
Is it possible?
Since you are using a generic in the form of an Iterable<T>, you may need to use:
String jsonString = gson.toJson(proveedoresList, typeOfSrc);
Where typeOfSrc is the type of your proveedoresList. that way gson knows how to serialize the object properly.
To print the neccesary details we used the following command
System.out.println(msgFromServer.data);
Now the following details are fetched from server
[{id={name=XDA Studio, color=red}, angle=-0.24456912236854822, piecePosition={pieceIndex=39.0, inPieceDistance=35.797426838065036, lane={startLaneIndex=1.0, endLaneIndex=1.0}, lap=2.0}}]
How to store these above server messages in json array variable and print value of angle alone.
msgFromServer.data seems to return a List. Your List is something like
List<Map<String,Object>>
If you use Jackson parser, you could probably convert it to a Json String using the following code:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(list);
I have provided code for Jackson library, you could use any other with library specific implementation and code
I need to parse json response in a play application and get all the fields/values in a list.
I'm getting the response as below:
WSRequestHolder request = WS.url("someurl");
request.setQueryParameter("somekey", "somevalue");
Promise<Response> promise = request.get();
Response response = promise.get();
JsonNode json = response.asJson();
The response comes like below:
{"results":{"key1":value1,"key2":value2,"key3":value3},"errorMessage":"","statusCode":2000,"success":true,"version":"1.01"}
I need to get all the feilds/values from "results" list. How can i do this using play json libraries / apis available? I'm using play 2.1.1.
Thanks.
Since the result is a JsonNode, you have all the niceties of JsonNode available to you.
For instance, if you want to access "results", do:
JsonNode results = json.get("results");
You also have methods such as .has(), .path(), .entries(), etc etc. One JsonNode can represent any JSON value, including null.
To test the type you can use the .is*() methods: .isObject(), .isNumber(), .isMissing() (note: the latter requires the use of .path() instead of .get()).
Example:
json.path("foo").isMissing(); // true
json.path("errorMessage").getTextValue(); // ""
json.get("results").get("key2"); // value2
json.get("success").getBooleanValue(); // true
Etc etc. See the javadoc for JsonNode.
Another solution would be to deserialize that JSON into a POJO. But that means creating the POJO in the first place, and then use an ObjectMapper to .read*() the value.
(side note: it is surprising that Play uses Jackson 1.9.x whereas 2.0+ has been available for many years...)
I am working with a big JSON object which has responses form multiple requests.
And the part I am working on requires only few object and they are not always in front.
For Example the json structure is:
**
json = {
mainDocument: {
element1: {
element11: "value11",
element12: {
element121: "value121"
}
},
element2: {
element21: {
element211: {
element2111: "value2111",
element2112: {
element21121: "value21121"
}
}
},
element22: "value22"
}
}
}
**
This structure can change depending on whether or not the request is successful.
Now,
I want to create an java object with the value of element11, element 22, element21121.
Currently I just check the json and use the setters of the object.
I want to know if there is a way to let GSON handle this and not have to parse the json myself.
Thanks in advance for any help you can offer.
I don't know if I understand your question very well, but in order to deserialize a JSON response with Gson, the most proper way in my opinion is to create a class structure that encapsulates the data in the response. In your case something like:
class Response
MainDocument mainDocument
class MainDocument
Element element1
Element element2
class Element
...
If you only need some data from the JSON, you can omit attributes in your class structure and Gson will ignore them. And if an object can have different contents in different responses, you can have something like this:
class Response
MainDocument mainDocument
Error error
And Gson will parse responses both with a root element mainDocument (like the one in the question) or with a root element error... this allows you to adapt your parsing to variable responses...
Obviously, to follow this approach, you need to know all the possible response structures you can have. If your problem is that your JSON response is absolutely variable, and you cannot create a class struture to wrap it, you always could do a manual parsing, somehting like this:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(jsonString).getAsJsonObject();
String element21121 = rootObj
.getAsJsonObject("mainDocument")
.getAsJsonObject("element2")
.getAsJsonObject("element21")
.getAsJsonObject("element211")
.getAsJsonObject("element2112")
.getAsString("element21121");