Parsing JSON array into java.util.List with Gson
Definitely the easiest way to do that is using Gson's default parsing function fromJson()
.
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType
(e.g., any List
), which is fromJson(JsonElement json, Type typeOfT)
.
In your case, you just need to get the Type
of a List<String>
and then parse the JSON array into that Type
, like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case yourJson
is a JsonElement
, but it could also be a String
, any Reader
or a JsonReader
.
You may want to take a look at Gson API documentation.
How to convert JSONArray to List with Gson?
If you see the answer there, you can notice that the first parameter in the fromJson()
method was a String
(the json object). Try to use the toString()
on the JsonArray like this:-
List<MyModel> myModelList = gson.fromJson(jsonArray.toString(), listType);
Error parsing JSON data to an array using GSON
You cannot convert your jsonObject in an Array you must have a jsonArray to do this. Simply add this lines:
JsonObject jsonObject = gson.fromJson(jsonResponse, JsonObject.class);
String articlesArrayResponse = jsonObject.getAsJsonArray("articles").getAsString();
before your exception happens. Obviously you must change the argument in that line for this:
Collection<ArticleResponse> enums = gson.fromJson(articlesArrayResponse, collectionType);
I hope it helps you!
How to Parse JSON Array with Gson
You can parse the JSONArray
directly, don't need to wrap your Post
class with PostEntity
one more time and don't need new JSONObject().toString()
either:
Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);
Hope that helps.
Gson - convert from Json to a typed ArrayListT
You may use TypeToken to load the json string into a custom object.
logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());
Documentation:
Represents a generic type T.
Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
For example, to create a type literal for
List<String>
, you can create an empty anonymous inner class:
TypeToken<List<String>> list = new TypeToken<List<String>>() {};
This syntax cannot be used to create type literals that have wildcard parameters, such as
Class<?>
orList<? extends CharSequence>
.
Kotlin:
If you need to do it in Kotlin you can do it like this:
val myType = object : TypeToken<List<JsonLong>>() {}.type
val logs = gson.fromJson<List<JsonLong>>(br, myType)
Or you can see this answer for various alternatives.
how to read an array of object from json using gson?
You are passing the file path as a parameter into the Gson constructor.
You must pass the JsonReader object into the Gson constructor as a parameter.
JsonReader reader= new JsonReader(new FileReader(path));
SupportPosition[] a=new Gson().fromJson(reader, SupportPosition[].class);
try this and let me know.
Recover JSON array from java.util.List with Gson
In the Build class
public class Build {
private AutomationBuild automationBuild = new AutomationBuild();
the automationBuild
should be automation_build
.It should be like
public class Build {
private AutomationBuild automation_build= new AutomationBuild();
as the Json looks like
"automation_build": {
java.lang.IllegalStateException:JSON OBJECT and JSON ARRAY when parsing Json using GSON
The retrofit interface:
interface APIInterface {
@GET("Company.php")
fun getCompanyData() : Observable<List<CompanyList>>
}
Hints retrofit that you expect a list of CompanyList
. However, the json you receive is a single CompanyList
. This is what the gson error your getting tells you - Expected to begin with an array but it was an object.
Changing the retrofit interface to:
interface APIInterface {
@GET("Company.php")
fun getCompanyData() : Observable<CompanyList>
}
will hint retrofit that you expect a single object of type CompanyList
and this should work for the json you've posted.
How to use Gson to parse JSON file that contains arrays
Loop through the JsonObject
entrySet
and add each JsonArray
into the list, I use my Java code, you can convert it to Kotlin if need:
ArrayList<JsonArray> result = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : resultJson.entrySet()) {
if (entry.getValue().isJsonArray()) {
result.add(entry.getValue().getAsJsonArray());
}
}
Related Topics
How to Obtain Mouse Click Coordinates Outside My Window in Java
Providing Input/Subcommands to Command Executed Over Ssh with Jsch
Bytebuffer.Allocate() VS. Bytebuffer.Allocatedirect()
How to Remove Single Character from a String
How to Print Formatted Bigdecimal Values
Tokenizing a String But Ignoring Delimiters Within Quotes
Java Swing: How to Change Gui Dynamically
How to Convert a 3D Point into 2D Perspective Projection
Performance Differences Between Arraylist and Linkedlist
Using Internal Sun Classes with Javac
Change Background Color of One Cell in Jtable
Naming Threads and Thread-Pools of Executorservice
Filter Values Only If Not Null Using Lambda in Java8
What Is the --Release Flag in the Java 9 Compiler
Windows Shortcut (.Lnk) Parser in Java