I have a JSON response that looks like this:
{
"result": {
"map": {
"entry": [
{
"key": { "#xsi.type": "xs:string", "$": "ContentA" },
"value": "fsdf"
},
{
"key": { "#xsi.type": "xs:string", "$": "ContentB" },
"value": "dfdf"
}
]
}
}
}
I want to access the value of the "entry" array object. I am trying to access:
RESPONSE_JSON_OBJECT.getJSONArray("entry");
I am getting JSONException. Can someone please help me get the JSON array from the above JSON response?
You have to decompose the full object to reach the entry array.
Assuming REPONSE_JSON_OBJECT is already a parsed JSONObject.
REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
Try this code using Gson library and get the things done.
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(JsonString, JsonObject.class);
JsonElement entry=job.getAsJsonObject("results").getAsJsonObject("map").getAsJsonArray("entry");
String str = entry.toString();
System.out.println(str);
I suggest you to use Gson library. It allows to parse JSON string into object data model. Please, see my example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
public class GsonProgram {
public static void main(String... args) {
String response = "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"#xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"#xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}";
Gson gson = new GsonBuilder().serializeNulls().create();
Response res = gson.fromJson(response, Response.class);
System.out.println("Entries: " + res.getResult().getMap().getEntry());
}
}
class Response {
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
#Override
public String toString() {
return result.toString();
}
}
class Result {
private MapNode map;
public MapNode getMap() {
return map;
}
public void setMap(MapNode map) {
this.map = map;
}
#Override
public String toString() {
return map.toString();
}
}
class MapNode {
List<Entry> entry = new ArrayList<Entry>();
public List<Entry> getEntry() {
return entry;
}
public void setEntry(List<Entry> entry) {
this.entry = entry;
}
#Override
public String toString() {
return Arrays.toString(entry.toArray());
}
}
class Entry {
private Key key;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
#Override
public String toString() {
return "[key=" + key + ", value=" + value + "]";
}
}
class Key {
#SerializedName("$")
private String value;
#SerializedName("#xsi.type")
private String type;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "[value=" + value + ", type=" + type + "]";
}
}
Program output:
Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]
If you not familiar with this library, then you can find a lot of informations in "Gson User Guide".
This is for Nikola.
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
JSONObject j;
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
break;
}
}
}
}
return js1;
}
public static void main(String[] args) throws IOException, JSONException {
String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
JSONObject json = new JSONObject(text);
setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
System.out.println(json.toString(4));
}
If it's help bro,Do not forget to up for my reputation)))
You can try this:
JSONObject result = new JSONObject("Your string here").getJSONObject("result");
JSONObject map = result.getJSONObject("map");
JSONArray entries= map.getJSONArray("entry");
I hope this helps.
I'm also faced with this issue. So I solved with recursion. Maybe it will be helpfull.
I created method.I used org.json library.
public static JSONObject function(JSONObject obj, String keyMain, String newValue) throws Exception {
// We need to know keys of Jsonobject
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if object is just string we change value in key
if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
function(obj.getJSONObject(key), keyMain, valueMain, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i=0;i<jArray.length();i++) {
function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
}
}
}
return obj;
}
if you have questions, I can explain...
I would also try it this way
1) Create the Java Beans from the JSON schema
2) Use JSON parser libraries to avoid any sort of exception
3) Cast the parse result to the Java object that was created from the initial JSON schema.
Below is an example JSON Schema"
{
"USD" : {"15m" : 478.68, "last" : 478.68, "buy" : 478.55, "sell" : 478.68, "symbol" : "$"},
"JPY" : {"15m" : 51033.99, "last" : 51033.99, "buy" : 51020.13, "sell" : 51033.99, "symbol" : "¥"},
}
Code
public class Container {
private JPY JPY;
private USD USD;
public JPY getJPY ()
{
return JPY;
}
public void setJPY (JPY JPY)
{
this.JPY = JPY;
}
public USD getUSD ()
{
return USD;
}
public void setUSD (USD USD)
{
this.USD = USD;
}
#Override
public String toString()
{
return "ClassPojo [JPY = "+JPY+", USD = "+USD+"]";
}
}
public class JPY
{
#SerializedName("15m")
private double fifitenM;
private String symbol;
private double last;
private double sell;
private double buy;
public double getFifitenM ()
{
return fifitenM;
}
public void setFifitenM (double fifitenM)
{
this.fifitenM = fifitenM;
}
public String getSymbol ()
{
return symbol;
}
public void setSymbol (String symbol)
{
this.symbol = symbol;
}
public double getLast ()
{
return last;
}
public void setLast (double last)
{
this.last = last;
}
public double getSell ()
{
return sell;
}
public void setSell (double sell)
{
this.sell = sell;
}
public double getBuy ()
{
return buy;
}
public void setBuy (double buy)
{
this.buy = buy;
}
#Override
public String toString()
{
return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
}
}
public class USD
{
#SerializedName("15m")
private double fifitenM;
private String symbol;
private double last;
private double sell;
private double buy;
public double getFifitenM ()
{
return fifitenM;
}
public void setFifitenM (double fifitenM)
{
this.fifitenM = fifitenM;
}
public String getSymbol ()
{
return symbol;
}
public void setSymbol (String symbol)
{
this.symbol = symbol;
}
public double getLast ()
{
return last;
}
public void setLast (double last)
{
this.last = last;
}
public double getSell ()
{
return sell;
}
public void setSell (double sell)
{
this.sell = sell;
}
public double getBuy ()
{
return buy;
}
public void setBuy (double buy)
{
this.buy = buy;
}
#Override
public String toString()
{
return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
}
}
public class MainMethd
{
public static void main(String[] args) throws JsonIOException, JsonSyntaxException, FileNotFoundException {
// TODO Auto-generated method stub
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("C:\\Users\\Documents\\file.json"));
String res = obj.toString();
Gson gson = new Gson();
Container container = new Container();
container = gson.fromJson(res, Container.class);
System.out.println(container.getUSD());
System.out.println("Sell Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getSell());
System.out.println("Buy Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getBuy());
}
}
Output from the main method is:
ClassPojo [15m = 478.68, symbol = $, last = 478.68, sell = 478.68, buy = 478.55]
Sell Price : $478.68
Buy Price : $478.55
Hope this helps.
Related
For some reasons i get null pointer errors in the code down. I'm working with a book of examples and trying to make smth mine, but seems like theres a change in java or mistake in book.
I'm making a Chatbot(sort of AI) and can't get it working in java. When i run the program it lets me only write Hi and then it replays.
When i try to give him another word like engi he acts like i always say hi.
If i restart and write first engi, then the error pops up, null pointer for some reason.
Can anyone help?
import java.io.IOException;
import java.util.Scanner;
import org.apache.http.client.ClientProtocolException;
import com.google.gson.*;
public class engibot
{
JsonObject context;
public static void main (String[] args) {
engibot c= new engibot();
Scanner scanner= new Scanner(System.in);
String userUtterance;
do {
System.out.print("User:");
userUtterance=scanner.nextLine();
//end conversation
if (userUtterance.equals("QUIT")) {break;}
JsonObject userInput=new JsonObject();
userInput.add("userUtterance", new JsonPrimitive(userUtterance));
JsonObject botOutput = c.process(userInput);
String botUtterance = "";
if(botOutput !=null && botOutput.has("botUtterance")) {
botUtterance = botOutput.get("botUtterance").getAsString();
}
System.out.println("Bot:" + botUtterance);
}while(true);
scanner.close();
}
public engibot() {
context =new JsonObject();
}
public JsonObject process(JsonObject userInput) {
//step 1: process user input
JsonObject userAction = processUserInput(userInput);
//step 2: update context
updateContext(userAction);
//step 3: identify bot intent
identifyBotIntent();
//step 4: structure output
JsonObject out = getBotOutput();
return out;
}
public JsonObject processUserInput(JsonObject userInput) {
String userUtterance = null;
JsonObject userAction = new JsonObject();
//default case
userAction.add("userIntent", new JsonPrimitive(""));
if(userInput.has("userUtterance")) {
userUtterance= userInput.get("userUtterance").getAsString();
userUtterance=userUtterance.replaceAll("%2C", ",");
}
if (userUtterance.matches("(hi)|(hi | hello)( there)?")) {
userAction.add("userIntent", new JsonPrimitive("greet"));
}
else if (userUtterance.matches("(thanks)|(thank you)")) {
userAction.add("userIntent", new JsonPrimitive("thank"));
}
else if(userUtterance.matches("(engi) | (engagment)")) {
userAction.add("userIntent", new JsonPrimitive("request_engi"));
}
else {
//contextual processing
String currentTask = context.get("currentTask").getAsString();
String botIntent = context.get("botIntent").getAsString();
if(currentTask.equals("requestEngi") && botIntent.equals("requestUserName")) {
userAction.add("userIntent", new JsonPrimitive("inform_name"));
userAction.add("userName", new JsonPrimitive(userUtterance));
}
}
return userAction;
}
public void updateContext(JsonObject userAction) {
//copy userIntent
context.add("userIntent", userAction.get("userIntent"));
String userIntent = context.get("userIntent").getAsString();
if(userIntent.equals("greet")) {
context.add("currentTask", new JsonPrimitive("greetUser"));
}else if (userIntent.equals("request_engi")) {
context.add("currentTask", new JsonPrimitive("requestEngi"));
}else if (userIntent.equals("infrom_city")) {
String userName = userAction.get("userName").getAsString();
Engi userInfo = DB.getUserInfo(userName);
if(!userInfo.get("userName").isJsonNull()) {
context.add("placeOfWeather", userInfo.get("cityCode"));
context.add("placeName", userInfo.get("cityName"));
}
}else if (userIntent.equals("thank")) {
context.add("currenTask", new JsonPrimitive("thankUser"));
}
}
public void identifyBotIntent() {
String currentTask = context.get("currentTask").getAsString();
if(currentTask.equals("greetUser")) {
context.add("botIntent", new JsonPrimitive("greetUser"));
}else if(currentTask.equals("thankUser")) {
context.add("botIntent", new JsonPrimitive("thankUser"));
}else if (currentTask.equals("requestEngi")) {
if (context.get("userName").getAsString().equals("unknown")) {
context.add("botIntent", new JsonPrimitive("requestUserName"));
}
else {
Integer time = -1;
if (context.get("").getAsString().equals("current")) {
time=0;
}
Engi userReport =null;
userReport = DB.getUserInfo(
context.get("userName").getAsString());
if(userReport !=null) {
context.add("userReport", new JsonPrimitive("userReport"));
context.add("botIntent", new JsonPrimitive("informUser"));
}
}
}else {
context.add("botIntent", null);
}
}
public JsonObject getBotOutput() {
JsonObject out=new JsonObject();
String botIntent = context.get("botIntent").getAsString();
String botUtterance="";
if(botIntent.equals("greetUser")) {
botUtterance= "Hi there! I am EngiMan, your engagement bot! " + "What would you like to do? Engage someone or something else?";
}else if(botIntent.equals("thankUser")) {
botUtterance="Thanks for talking to me! Have a great day!!";
}else if (botIntent.equals("requestName")) {
botUtterance="Ok. What's his name?";
}else if(botIntent.equals("informUser")) {
String userDescription= getUserDescription(context.get("userName").getAsString());
String engiIndex= getEngiIndex();
botUtterance = "Ok. "+"Engagment index of "+userDescription+" is"+engiIndex+".";
}
out.add("botIntent", context.get("botIntent"));
out.add("botUtterance", new JsonPrimitive(botUtterance));
return out;
}
private String getEngiIndex() {
return context.get("engiIndex").getAsString();
}
private String getUserDescription(String userName) {
if (userName.equals("current")) {
return "current";
}
return null;
}
}
import com.google.gson.JsonElement;
public class Engi {
private String Name;
private String LastName;
private int Age;
private double EngiIndex;
private String Firm;
private String Team;
public JsonElement get(String string) {
// TODO Auto-generated method stub
return null;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lasteName) {
LastName = lasteName;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public double getEngiIndex() {
return EngiIndex;
}
public void setEngiIndex(double engiIndex) {
EngiIndex = engiIndex;
}
public String getFirm() {
return Firm;
}
public void setFirm(String firm) {
Firm = firm;
}
public String getTeam() {
return Team;
}
public void setTeam(String team) {
Team = team;
}
}
How to parse this kind of json?
{
"tId": 5439661,
"name": "aASD",
"inputParameters": {
"a": "50",
"b": "234324",
"c": "wefefew",
"d": "T",
"e": "4224",
"f": "T",
"g": "t"
},
"outputParameters": {
"dId": "{1234435-A333F-A3334-A273-123243252355}",
"fd": "1000023456"
}
}
Parsing code:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response.body().toString());
} catch (JSONException e) {
e.printStackTrace();
}
I tried like above but I get this error:
org.json.JSONException: Expected ':' after 1234435-A333F-A3334-A273-123243252355
I tried with POJO and gson library but still with no success
Anybody has solved this kind of problem?
How can I get "dId" as string?
Edited: Posted response from server for testing
Use this Model:-
And use Gson First Include library of Gson Before using it
dependencies {
implementation 'com.google.code.gson:gson:2.8.2' // Old 2.8.0
}
Gson gson = new Gson();
RootObject rootObject = new RootObject();
rootObject = gson.fromJson("Your json string or content", RootObject.class)
public class InputParameters
{
private String a;
public String getA() { return this.a; }
public void setA(String a) { this.a = a; }
private String b;
public String getB() { return this.b; }
public void setB(String b) { this.b = b; }
private String c;
public String getC() { return this.c; }
public void setC(String c) { this.c = c; }
private String d;
public String getD() { return this.d; }
public void setD(String d) { this.d = d; }
private String e;
public String getE() { return this.e; }
public void setE(String e) { this.e = e; }
private String f;
public String getF() { return this.f; }
public void setF(String f) { this.f = f; }
private String g;
public String getG() { return this.g; }
public void setG(String g) { this.g = g; }
}
public class OutputParameters
{
private String dId;
public String getDId() { return this.dId; }
public void setDId(String dId) { this.dId = dId; }
private String fd;
public String getFd() { return this.fd; }
public void setFd(String fd) { this.fd = fd; }
}
public class RootObject
{
private int tId;
public int getTId() { return this.tId; }
public void setTId(int tId) { this.tId = tId; }
private String name;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
private InputParameters inputParameters;
public InputParameters getInputParameters() { return this.inputParameters; }
public void setInputParameters(InputParameters inputParameters) { this.inputParameters = inputParameters; }
private OutputParameters outputParameters;
public OutputParameters getOutputParameters() { return this.outputParameters; }
public void setOutputParameters(OutputParameters outputParameters) { this.outputParameters = outputParameters; }
}
Just write
String text= response.getString("dId");
and then text will be: {1234-123423-53235423} and you can do every thing with this text.
I solve your problem with this code example and my code work fine.
public void getjson() {
RequestQueue mQueue;
mQueue = Volley.newRequestQueue(MainActivity.this);
String url = "http://www.mocky.io/v2/5b28ca862f00006300f55e6e";
JsonObjectRequest request = new JsonObjectRequest(com.android.volley.Request.Method.GET, url, null, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response", response.toString());
if(response.length()>0){
String id=response.getString("tId");
String name=response.getString("name");
Log.d("response.getid",id);
Log.d("response.getname",name);
JSONObject inputObject=response.getJSONObject("inputParameters");
if(inputObject.length()>0){
String a=inputObject.getString("a");
String b=inputObject.getString("b");
String c=inputObject.getString("c");
String d=inputObject.getString("d");
String e=inputObject.getString("e");
String f=inputObject.getString("f");
String g=inputObject.getString("g");
}
JSONObject outObject=response.getJSONObject("outputParameters");
if(outObject.length()>0){
String didText=outObject.getString("dId");
String fdText=outObject.getString("fd");
Log.d("response.getstring",didText);
Log.d("response.getstring",fdText);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", "Error de response");
error.printStackTrace();
}
});
mQueue.add(request);
}
I have json like:
{"avatars": {
"1": "value",
"2":"value",
"900":"value"
}
}
And my model:
class Response{
List<Avatar> avatars;
}
class Avatar{
String id;
String value;
}
How do I properly parse the Json using Jackson
You should use json like this to automaticaly parse:
{"avatars": [
{"id": "1", "value": "someValue1"},
{"id": "2", "value": "someValue2"},
{"id": "300", "value": "someValue300"},
]
}
or write custom parser for Jackson.
Try this:
Using Java JSON library
public class Test {
public static void main(String[] args) {
Response response = new Response();
Serializer.serialize("{\"avatars\": { \"1\": \"value\", \"2\":\"value\", \"900\":\"value\" }}", response);
System.out.println(response.toString());
}
}
class Serializer {
public static void serialize(String j, Response response) {
try {
JSONObject json = new JSONObject(j).getJSONObject("avatars");
Iterator keys = json.keys();
while (keys.hasNext()) {
String id = keys.next().toString();
String value = json.getString(id);
response.addAvatar(id, value);
}
} catch (JSONException ignore) {
}
}
}
/**
* This is a response class
*/
class Response {
List<Avatar> avatars;
public Response() {
/**
* You can use LinkedList, I think it's the best way.
*/
this.avatars = new LinkedList<Avatar>();
}
public void addAvatar(String id, String value) {
this.avatars.add(new Avatar(id, value));
}
public String toString() {
String result = "";
for (Avatar avatar : this.avatars) {
result += (result.length() == 0 ? "" : ", ") + "[" + avatar.getId() + "=" + avatar.getValue() + "]";
}
return result;
}
}
/**
* This is an avatar class
*/
class Avatar {
private String id;
private String value;
public Avatar(String id, String value) {
this.id = id;
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Hope this helps!
You can just use a converter, which avoids the complexity of a full custom deserializer:
#JsonDeserialize(converter = AvatarMapConverter.class)
public List<Avatar> avatars;
The converter needs to declare that it can accept some other type that Jackson can deserialize to, and produce a List<Avatar>. Extending StdConverter will do the plumbing for you:
public class AvatarMapConverter extends StdConverter<Map<String, String>, List<Avatar>> {
#Override
public List<Avatar> convert(Map<String, String> input) {
List<Avatar> output = new ArrayList<>(input.size());
input.forEach((id, value) -> output.add(new Avatar(id, value)));
return output;
}
}
If you need to serialize too, you can write a converter to go the other way and reference that from a #JsonSerialize annotation.
I'm trying deserializes a JSONArray to List. To do it I'm trying use Gson but I can't understand why doesn't works and all values of JSON are null.
How could I do this ?
JSON
{ "result" : [
{ "Noticia" : {
"created" : "2015-08-20 19:58:49",
"descricao" : "tttttt",
"id" : "19",
"image" : null,
"titulo" : "ddddd",
"usuario" : "FERNANDO PAIVA"
} },
{ "Noticia" : {
"created" : "2015-08-20 19:59:57",
"descricao" : "hhhhhhhh",
"id" : "20",
"image" : "logo.png",
"titulo" : "TITULO DA NOTICIA",
"usuario" : "FERNANDO PAIVA"
} }
] }
Deserializes
List<Noticia> lista = new ArrayList<Noticia>();
Gson gson = new Gson();
JSONArray array = obj.getJSONArray("result");
Type listType = new TypeToken<List<Noticia>>() {}.getType();
lista = gson.fromJson(array.toString(), listType);
//testing - size = 2 but value Titulo is null
Log.i("LISTSIZE->", lista.size() +"");
for(Noticia n:lista){
Log.i("TITULO", n.getTitulo());
}
Class Noticia
public class Noticia implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String titulo;
private String descricao;
private String usuario;
private Date created;
private String image;
There are two problems with your code :
First is that you are using a getJsonArray() to get the array,
which isn't part of Gson library, you need to use
getAsJsonArray() method instead.
Second is that you are using array.toString() which isn't obvious
because for the fromJson method you need a jsonArray as
parameter and not String and that will cause you parse problems, just remove it.
And use the following code to convert your jsonArray to List<Noticia> :
Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);
And your whole code will be:
Gson gson = new Gson();
JSONArray array = obj.getAsJsonArray("result");
Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);
//testing - size = 2 but value Titulo is null
Log.i("LISTSIZE->", lista.size() +"");
for(Noticia n:lista){
Log.i("TITULO", n.getTitulo());
}
I think the problem could be something to do with toString() on JSONArray. But are you using obj.getAsJsonArray method?
Try this:
JSONArray arr = obj.getAsJsonArray("result");
Type listType = new TypeToken<List<Noticia>>() {
}.getType();
return new Gson().fromJson(arr , listType);
Noticia.java
public class Noticia {
private String created;
private String descricao;
private String id;
private String image;
private String titulo;
private String usuario;
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
#Override
public String toString() {
return "Noticia [created=" + created + ", descricao=" + descricao
+ ", id=" + id + ", image=" + image + ", titulo=" + titulo
+ ", usuario=" + usuario + "]";
}
}
Result.java
public class Result {
private Noticia Noticia;
public Noticia getNoticia() {
return Noticia;
}
public void setNoticia(Noticia noticia) {
Noticia = noticia;
}
#Override
public String toString() {
return "Result [Noticia=" + Noticia + "]";
}
}
Item.java
import java.util.List;
public class Item {
private List<Result> result;
public List<Result> getResult() {
return result;
}
public void setResult(List<Result> result) {
this.result = result;
}
#Override
public String toString() {
return "Item [result=" + result + "]";
}
}
Main.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Item;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
public static void main(String[] args) {
String j = "{\"result\":[{\"Noticia\":{\"created\":\"2015-08-20 19:58:49\",\"descricao\":\"tttttt\",\"id\":\"19\",\"image\":null,\"titulo\":\"ddddd\",\"usuario\":\"FERNANDO PAIVA\"}},{\"Noticia\":{\"created\":\"2015-08-20 19:59:57\",\"descricao\":\"hhhhhhhh\",\"id\":\"20\",\"image\":\"logo.png\",\"titulo\":\"TITULO DA NOTICIA\",\"usuario\":\"FERNANDO PAIVA\"}}]}";
Item r = gson.fromJson(j, Item.class);
System.out.println(r);
}
}
Final result
Item [result=[Result [Noticia=Noticia [created=2015-08-20 19:58:49, descricao=tttttt, id=19, image=null, titulo=ddddd, usuario=FERNANDO PAIVA]], Result [Noticia=Noticia [created=2015-08-20 19:59:57, descricao=hhhhhhhh, id=20, image=logo.png, titulo=TITULO DA NOTICIA, usuario=FERNANDO PAIVA]]]]
You parse json, that looks like
{ "result" : [
{
"created" : "2015-08-20 19:58:49",
"descricao" : "tttttt",
"id" : "19",
"image" : null,
"titulo" : "ddddd",
"usuario" : "FERNANDO PAIVA"
},
{
"created" : "2015-08-20 19:59:57",
"descricao" : "hhhhhhhh",
"id" : "20",
"image" : "logo.png",
"titulo" : "TITULO DA NOTICIA",
"usuario" : "FERNANDO PAIVA"
}
] }
You need to make another object Item and parse a list of them.
public class Item{
Noticia noticia;
}
Or you can interate through JSONArray, get field "noticia" from each then parse Noticia object from given JSONObject.
Kotlin Ex :
we getting response in form of JSONArry
call.enqueue(object : Callback<JsonArray> {
override fun onResponse(call: Call<JsonArray>, response: Response<JsonArray>) {
val list = response.body().toString()
val gson = Gson()
val obj: CitiesList? = gson.fromJson(list, CitiesList::class.java)
cityLiveData.value = obj!!
}
override fun onFailure(call: Call<JsonArray>, t: Throwable) {
}
})
Here CitiesList CitiesList::class.java is the ArrayList of Cities object
class CitiesList : ArrayList<CitiesListItem>()
Before using GSON add dependancey in Gradle
dependencies {
implementation 'com.google.code.gson:gson:2.8.8'
}
I have created a json which have a root node with couple of child nodes using java now i have a requirement that the child node under the root may also have some children.But i am unable to do that.Here is what i have done so far....
class Entry {
private String name;
public String getChildren() {
return name;
}
public void setChildren(String name) {
this.name = name;
}
}
public class JsonApplication {
public static void main(String[] args) {
// TODO code application logic here
String arr[] = {"Culture", "Salary", "Work", "Effort"};
EntryListContainer entryListContainer = new EntryListContainer();
List<Entry> entryList1 = new ArrayList<>();
List<Entry> entryList2 = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
Entry entry1 = new Entry();
entry1.setChildren(arr[i]);
entryList1.add(entry1);
entryList2.add(entry1);
/*Child nodes are created here and put into entryListContainer*/
entryListContainer.setEntryList1(entryList1);
entryListContainer.setEntryList1(entryList2);
}
/*Root node this will collapse and get back to Original position on click*/
entryListContainer.setName("Employee");
entryListContainer.setName("Culture");
Map<String, String> mapping = new HashMap<>();
mapping.put("entryList1", "name");
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping)).create();
System.out.println(gson.toJson(entryListContainer));
}
}
class DynamicFieldNamingStrategy implements FieldNamingStrategy {
private Map<String, String> mapping;
public DynamicFieldNamingStrategy(Map<String, String> mapping) {
this.mapping = mapping;
}
#Override
public String translateName(Field field) {
String newName = mapping.get(field.getName());
if (newName != null) {
return newName;
}
return field.getName();
}
}
class EntryListContainer {
private List<Entry> children;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setEntryList1(List<Entry> entryList1) {
this.children = entryList1;
}
public List<Entry> getEntryList1() {
return children;
}
}
This is the json output i am getting
{
"children": [
{
"name":"Culture"
},
{
"name":"Salary"
},
{
"name":"Work"
},
{
"name":"Effort"
}
],
"name":"Employee"
}
But i need
{
"name":"Culture",
"children":[
{
"name":"Culture"
},
{
"name":"Salary"
},
{
"name":"Work"
},
{
"name":"Effort"
}
],
"name":"Work",
"children" : [
{
"name":"Culture"
},
{
"name":"Work"
}
]
}
I'm a bit confused by your code, but something is clear to me: what you want to get. So starting from scratch I created some code you can copy&run to see how you can get your desired JSON.
Probably the order of elements is important for you (pay attention that in JSON object order of keys is not important -is a map!-), so I edited some code that is not pure Gson way of doing things but that creates exactly your example.
package stackoverflow.questions;
import java.lang.reflect.Field;
import java.util.*;
import com.google.gson.*;
public class JsonApplication {
public static class EntryListContainer {
public List<Entry> children = new ArrayList<Entry>();
public Entry name;
}
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
}
public static void main(String[] args) {
EntryListContainer elc1 = new EntryListContainer();
elc1.name = new Entry("Culture");
elc1.children.add(new Entry("Salary"));
elc1.children.add(new Entry("Work"));
elc1.children.add(new Entry("Effort"));
EntryListContainer elc2 = new EntryListContainer();
elc2.name = new Entry("Work");
elc2.children.add(new Entry("Culture"));
elc2.children.add(new Entry("Work"));
ArrayList<EntryListContainer> al = new ArrayList<EntryListContainer>();
Gson g = new Gson();
al.add(elc1);
al.add(elc2);
StringBuilder sb = new StringBuilder("{");
for (EntryListContainer elc : al) {
sb.append(g.toJson(elc.name).replace("{", "").replace("}", ""));
sb.append(",");
sb.append(g.toJson(elc.children));
sb.append(",");
}
String partialJson = sb.toString();
if (al.size() > 1) {
int c = partialJson.lastIndexOf(",");
partialJson = partialJson.substring(0, c);
}
String finalJson = partialJson + "}";
System.out.println(finalJson);
}
}
and this is the execution:
{"name":"Culture",[{"name":"Salary"},{"name":"Work"},{"name":"Effort"}],"name":"Work",[{"name":"Culture"},{"name":"Work"}]}