I have the following JSON in my android application and I'm using Springs for android RestTemplate. Is it somehow possible to fetch only internal list from this json ? Currently I have to create a wrapper object and then I can fetch List<Cast> casts; from it - it's a bit inconvenient.
{
"id": 550,
"cast": [
{
"cast_id": 4,
"character": "The Narrator",
"credit_id": "52fe4250c3a36847f80149f3",
"id": 819,
"name": "Edward Norton",
"order": 0,
"profile_path": "/iUiePUAQKN4GY6jorH9m23cbVli.jpg"
}
]
}
I know two solutions to solve this :
What you've done : Wrapping the list using a class
Write you're own JSON Deserializer, take a look here http://wiki.fasterxml.com/JacksonHowToCustomDeserializers
But I think the ultimate solution is in this post:
Spring/json: Convert a typed collection like List<MyPojo>
If Cast is a POJO you could try use the Jackson ObjectMapper class like this
ObjectMapper mapper = new ObjectMapper();
String jsonStr = ...
List<Cast> casts = mapper.readValue(jsonStr, new TypeReference<List<Cast>>(){});
You can grab the field, cast, and convert it like so:
final String json = "{\n" +
" \"id\": 550,\n" +
" \"cast\": [\n" +
" {\n" +
" \"cast_id\": 4,\n" +
" \"character\": \"The Narrator\",\n" +
" \"credit_id\": \"52fe4250c3a36847f80149f3\",\n" +
" \"id\": 819,\n" +
" \"name\": \"Edward Norton\",\n" +
" \"order\": 0,\n" +
" \"profile_path\": \"/iUiePUAQKN4GY6jorH9m23cbVli.jpg\"\n" +
" }\n" +
" ]\n" +
"}";
final List<Cast> casts;
try {
final JsonNode cast = objectMapper.readTree(json).get("cast");
casts = objectMapper.convertValue(cast, new TypeReference<List<Cast>>() {});
} catch (IOException e) {
throw Throwables.propagate(e);
}
Related
[
{
countryCode: "CN",
countryCallingCode: "+86",
codeRule: "^1\d{10}$"
},
{
countryCode: "US",
countryCallingCode: "+1",
codeRule: "^\d{10}$"
}
]
So I define the model like this in Kotlin
data class CountryCallingCode(
val countryCode: String,
val countryCallingCode: String,
val codeRule: String? = null
)
This is what the backend document defines the response.
codeRule is regex expression to verify a phone number.
I stuck in convert the String to List.
I pasted them to Android Studio, and it shows like:
String response = "[\n" +
" {\n" +
" countryCode: \"CN\",\n" +
" countryCallingCode: \"+86\",\n" +
//" codeRule: \"^1\\d{10}$\"\n" +
" },\n" +
" {\n" +
" countryCode: \"US\",\n" +
" countryCallingCode: \"+1\",\n" +
//" codeRule: \"^\\d{10}$\"\n" +
" }\n" +
"]";
The following codes do not work.
Converting code 1:
Gson gson = new Gson()
CountryCallingCode[] countryCallingCodeList = gson.fromJson(response, CountryCallingCode[].class);
And I think the following codes are the same, correct me if I am wrong.
Converting code 2:
ArrayList<CountryCallingCode> countryCallingCodeList = (ArrayList<CountryCallingCode>)gson.fromJson(response, ArrayList.class);
Converting Code 3
Gson gson = new Gson();
Type type = new TypeToken<List<CountryCallingCode>>() {
}.getType();
List<CountryCallingCode> countryCallingCodeList = gson.fromJson(response, type);
Then I use https://jsoneditoronline.org/ to reformat my json.
I tried to remove the codeRule, and pasted to the Android Studio, it also tells me I am wrong, it shows CountryCode causes SyntaxException.
String reponse = "[\n" +
" {\n" +
" countryCode: \"CN\",\n" +
" countryCallingCode: \"+86\"\n" +
" },\n" +
" {\n" +
" countryCode: \"US\",\n" +
" countryCallingCode: \"+1\"\n" +
" }\n" +
"]";
Only I compress the jsonstring to oneline, I could convert the jsonstring to the array/ArrayList.
String response = "[{\"countryCode\":\"CN\",\"countryCallingCode\":\"+86\"},{\"countryCode\":\"US\",\"countryCallingCode\":\"+1\"}]";
Does anyone know
Q1:
How to deal with codeRule?
Q2:
Why couldn't I pasted the origin JsonString to the Android Studio?
Why I must compress the JsonString into one line string?
Updated:
Origin one line json string:
[{"countryCode":"CN","countryCallingCode":"+86", codeRule: "^1\d{10}$"},{"countryCode":"US","countryCallingCode":"+1", codeRule: "^\d{10}$"}]
Pasted result json string:
String response = "[{\"countryCode\":\"CN\",\"countryCallingCode\":\"+86\", codeRule: \"^1\\d{10}$\"},{\"countryCode\":\"US\",\"countryCallingCode\":\"+1\", codeRule: \"^\\d{10}$\"}]";
Code:
Gson gson = new Gson();
/* Convertion 1 */
CountryCallingCode[] countryCallingCodeList = gson.fromJson(response, CountryCallingCode[].class);
Error:
result = {JsonSyntaxException#7237} Method threw 'com.google.gson.JsonSyntaxException' exception.
cause = {MalformedJsonException#7241} "com.google.gson.stream.MalformedJsonException: Invalid escape sequence at line 1 column 65 path $[0].codeRule"
detailMessage = "com.google.gson.stream.MalformedJsonException: Invalid escape sequence at line 1 column 65 path $[0].codeRule"
stackState = null
stackTrace = {StackTraceElement[28]#7243}
suppressedExceptions = {Collections$EmptyList#7244} size = 0
shadow$_klass_ = {Class#1694} "class com.google.gson.JsonSyntaxException"
shadow$_monitor_ = -2082115852
This is more of a comment than an answer, but I need more space to explain - if your version of Java supports it, can you try creating your response with a raw string like this:
String response = `[
{
countryCode: "CN",
countryCallingCode: "+86",
codeRule: "^1\d{10}$"
},
{
countryCode: "US",
countryCallingCode: "+1",
codeRule: "^\d{10}$"
}
]`
Or if possible use Kotlin, which uses """ to delimit raw strings. It will be much more readable and might help you spot mistakes
I am attempting to get the definition of a word using the documentation from Merriam Webster's API - https://dictionaryapi.com/products/json#sec-2.def
The documentation shows the structure of the JSON response from the server, and I have been able to successfully parse the raw data into a just an array containing the "sense" object.
Screenshot of code and parsed data
My issue is being able to access the "sense" JSONObject, since I am currently in an array, I can't access the sense object. I have tried adding .getJSONArray(0) and .getJSONObject(0) after my code and both of those solutions did not work.
How can I continue parsing this JSON I currently have to the "dt" string?
JSONArray merriamResults = data.getJSONArray("Merriam")
.getJSONObject(0)
.getJSONArray("def")
.getJSONObject(0)
.getJSONArray("sseq")
.getJSONArray(0)
.getJSONArray(0);
Here.
String json = "{\"def\":[\n" +
" {\n" +
" \"sseq\":[\n" +
" [\n" +
" [\n" +
" \"sense\",\n" +
" {\n" +
" \"dt\":[[\"text\",\"{bc}a {a_link|backward} somersault especially\n" +
" in the air\"]]\n" +
" }\n" +
" ]\n" +
" ]\n" +
" ]\n" +
" }\n" +
"]}";
try {
JSONObject jsonObject = new JSONObject(json);
String dt = jsonObject.getJSONArray("def")
.getJSONObject(0)
.getJSONArray("sseq")
.getJSONArray(0)
.getJSONArray(0)
.getJSONObject(1)
.getJSONArray("dt")
.getJSONArray(0)
.getString(1);
Log.i("jsondata", dt);
} catch (JSONException e) {
e.printStackTrace();
}
my log:
12-02 21:38:12.316 14174-14174/com.example.pemba.sample I/jsondata: {bc}a {a_link|backward} somersault especially
in the air
I got the following json:
{
"ID": "1234567",
"dangereousCargo": true,
"numberOfPassangers": 164,
"cargo": [
{
"type": "Oil",
"amount": 8556
},
{
"type": "Chemicals",
"amount": 5593
}
]
}
From this question, I understood that it is possible to get the cargoList out of the jsonObject (if that list contains a certain type of object). But how do I get the seperate cargoObjects out of that list?
+Do the variable names of the jsonstring have to correspond with the variable names in my CargoClass? What if the jsonObject only contains type and amount and my CargoClass has more attributes?
You can iterate throws the JSONArray which represents your cargo list doing (not tested)
JSONObject json = new JSONObject(jsonString);
JSONArray cargoList = json.getJSONArray("cargo");
for(int i=0; i< cargoList.length(); i++) {
JSONObject cargo = cargoList.getJSONObject(i);
//Do something with cargo
}
But how do I get the seperate cargoObjects out of that list?
String jsonString = "{ ... }";
JSONObject json = new JSONObject(jsonString);
JSONArray cargoList = json.getJSONArray("cargo");
for(JSONObject cargo : cargoList)
{
//do something with your cargo element
}
Do the variable names of the jsonstring have to correspond with the
variable names in my CargoClass?
If you use the the get method from the JSONObject, you have to specify the exact name of the attribute in your jsonString. Following the example above:
String cargoType = cargo.getString("type");
By the way, if you want to use your already defined CargoClass, you need a Deserializer and all the attributes on your JSON must be the all present and all the same on your CargoClass: I suggest you to take a look at other SOs questions like this one.
What if the jsonObject only contains type and amount and my CargoClass
has more attributes?
The other attributes will be initialize in base of your class declaration
Using JSON Simple it is very easy to parse and read your data from your JSON. As other users have said there are a plethora of libraries out there that can accomplish this. Below is a tested example of your code.
public static void main(String[] args) throws JSONException {
String json = "{\n"
+ " ID: 1234567,\n"
+ " dangereousCargo: true,\n"
+ " numberOfPassangers: 164,\n"
+ " cargo: [\n"
+ " {\n"
+ " type: Oil,\n"
+ " amount: 8556\n"
+ " },\n"
+ " {\n"
+ " type: Chemicals,\n"
+ " amount: 5593\n"
+ " }\n"
+ " ]\n"
+ "}";
JSONObject data = new JSONObject(json);
int id = data.getInt("ID");
boolean danger = data.getBoolean("dangereousCargo");
int numOfPassengers = data.getInt("numberOfPassangers");
System.out.println("Current ID: " + id + "\n"
+ "Is Dangerous: " + danger + "\n"
+ "Number of Passengers: " + numOfPassengers + "\n");
JSONArray cargo = data.getJSONArray("cargo");
NumberFormat currency = NumberFormat.getCurrencyInstance();
for (int i = 0; i < cargo.length(); i++) {
JSONObject cargoObject = cargo.getJSONObject(i);
String type = cargoObject.getString("type");
double amount = cargoObject.getDouble("amount");
System.out.println("Current Type: " + type);
System.out.println("Current Amount: " + currency.format(amount));
}
}
}
The above code gives us the following output:
Once you have your data you can really do whatever you want with it.
Libraries
JSONSimple-https://code.google.com/p/json-simple/
GSON-https://github.com/google/gson
I have already tried http://www.jsonschema2pojo.org/ to solve this but it hasn't worked. I am trying to create a Json response class for this Json format:
{
"Structure1": [
[
"StringValue1",
"StringValue2"
],
[
"StringValue1",
"StringValue2"
]
],
"Structure2": [
[
"StringValue1",
"StringValue2"
]
],
"Structure3": [
[
"StringValue1",
"StringValue2"
]
]
}
Here is what my current class looks like:
public class Response {
private HashMap<String, ArrayList<ArrayList<String>>> map = new HashMap<String, ArrayList<ArrayList<String>>>();
public HashMap<String, ArrayList<ArrayList<String>>> getMap() {
return map;
}
public void setFile11Txt(HashMap<String, ArrayList<ArrayList<String>>> map) {
this.map = map;
}
}
To parse I am doing
Response response = gson.fromJson(response, Response.class);
The returned map ends up being empty, what am I doing wrong?
I suggest the following code:
String jsonString = "{\n" +
" \"Structure1\": [\n" +
" [\n" +
" \"StringValue1\",\n" +
" \"StringValue2\"\n" +
" ],\n" +
" [\n" +
" \"StringValue1\",\n" +
" \"StringValue2\"\n" +
" ]\n" +
" ],\n" +
" \"Structure2\": [\n" +
" [\n" +
" \"StringValue1\",\n" +
" \"StringValue2\"\n" +
" ]\n" +
" ],\n" +
" \"Structure3\": [\n" +
" [\n" +
" \"StringValue1\",\n" +
" \"StringValue2\"\n" +
" ]\n" +
" ]\n" +
" }";
Map<String, ArrayList<String>> myMap = gson.fromJson(jsonString, HashMap.class);
Debug screenshot as the following:
Hope this helps!
Your Response represents and object that contains a HashMap in a field named map, but your JSON represents just a Map. You do not need to have an enclosing object, just deserialize the HashMap directly --
HashMap<String, ArrayList<ArrayList<String>>> map;
Type mapType = new TypeToken<HashMap<String, ArrayList<ArrayList<String>>>>() {}.getType();
map = gson.fromJson(response, mapType);
TypeToken objtype= new TypeToken<Response>() {}.getType();
Response responseobj= new Gson().fromJson(responsestring, objtype);
use Typetoken to parse Gson Object back to original one
{
"lastUpdated":1404620562,
"invasions":{
"Vibrant Valley":{
"asOf":1404620562,
"type":"Penny Pincher",
"progress":"959/1000"
}
},
"error":null
}
I'm new to using Json & Gson so be patient.
So I am attempting to make an application for myself that allows me to view the information from this json file. The only problem is that it is constantly changing and sometimes there will be more then one object under invasions or sometimes there will be none. How would I parse this with gson? Thanks. Note I am grabbing values from here.
https://www.toontownrewritten.com/api/invasions
Thanks!
Use the JsonParser class
String myJson = "{" +
" \"lastUpdated\":1404620562," +
" \"invasions\":{" +
" \"Vibrant Valley\":{" +
" \"asOf\":1404620562," +
" \"type\":\"Penny Pincher\"," +
" \"progress\":\"959/1000\"" +
" }" +
" }," +
" \"error\":null" +
"}"
JsonElement jelement = new JsonParser().parse(myJson);
JsonObject jobject = jelement.getAsJsonObject();
long lastUpdated = jobject.get("lastUpdated").getAsLong();