I am having trouble parsing my JSON which i get from javascript.
The format of JSON is this:
[{"positions":[{"x":50,"y":50},{"x":82,"y":50},{"x":114,"y":50},{"x":146,"y":50}]},{"positions":[{"x":210,"y":50},{"x":242,"y":50},{"x":274,"y":50}]}]
So far i have been able to get this far:
{"positions":[{"x":50,"y":50},{"x":82,"y":50},{"x":114,"y":50},{"x":146,"y":50}]}
But i also need to now create a class with those positions. I havnt been working on the class, since i tried printing out the output first, but i am unable to break it down further. I am getting this error message:
java.lang.IllegalStateException: This is not a JSON Array.
And my code is this:
JsonParser parser = new JsonParser();
String ships = request.getParameter("JSONships");
JsonArray array = parser.parse(ships).getAsJsonArray();
System.out.println(array.get(0).toString());
JsonArray array2 = parser.parse(array.get(0).toString()).getAsJsonArray();
System.out.println(array2.get(0).toString());
I have also tried to do it this way:
Gson gson = new Gson() ;
String lol = (gson.fromJson(array.get(0), String.class));
System.out.println(lol);
In which case i get:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT
In the end, i want to loop through positions, creating class for each "positions", which contains a List with another class Position, which has the int x, y.
Thank you for your time.
Define your classes and you will get everything you need using gson:
public class Class1 {
private int x;
private List<Class2> elements;
}
And the inner class:
public class Class2 {
private String str1;
private Integer int2;
}
Now you can parse a json string of the outer class just like that:
gson.fromJson(jsonString, Class1.class);
Your error while using Gson is that you try to parse a complex object in String, which is not possible.
Related
I have a JSON String as follows
{
"sort": [1000.0, "id123456789"]
}
I'm trying to deserialize this JSON String into an Object using GSON.fromJson(str, SortArray.class) but I don't know what to do since the JSON Array contains a double and a String, which are two different types.
Does anyone know how I could model this array in a class so I can deserialize it?
I have tried the following but it does not work
#Gson.TypeAdapters(nullAsDefault = true)
#Value.Immutable
public interface SortArray {
#Value.Parameter
double sortScore();
#Value.Parameter
String id();
}
I need to convert a json string to particular type based on the function's return type. The json string could also be a plain string. I am facing issues while converting the strings using gson.fromJson method.
Why is an exception thrown in gson.fromJson if the string contains a space? And how do I get around this?
import java.lang.reflect.Method;
import com.google.gson.Gson;
class Trial {
Object retu() {
return "BEVERLY OUTLAW";
}
}
public class sample {
public static void main (String args[]) {
Gson gson = new Gson();
Trial obj = new Trial();
Method func = obj.getClass().getDeclaredMethods()[0];
Object o = gson.fromJson("beverlyoutlaw", func.getGenericReturnType());
System.out.println(o); ---> this prints beverlyoutlaw
o = gson.fromJson("beverly outlaw", func.getGenericReturnType()); ---> This throws an exception!
System.out.println(o);
}
}
Strings in Json need to be surrounden by quotes. That is - in the Json itself!
Neither "beverlyoutlaw" nor "beverly outlaw" contain quotes in the string - the quotes are just part of the Java String literal.
Apparently Gson does not enforce this for strings without spaces - for strings with spaces however it is strictly necessary.
To fix your issue, use o = gson.fromJson("\"beverly outlaw\"", func.getGenericReturnType());
I'm a beginner in programming, and I need some help. Is it possible to convert an HTTP (that returns a Json) automatic call to object in java? For example it reads the request, and when I call System.out.println (obj) it already returns me an OBJECT of this request, instead of String. Is it possible? If so, could you help me ... I already did the method to call the url and return string, but I need to return OBJECT, so I can compare with HashCode and Equals.
My code:
enter image description here
output:
{"header":{"messageId":"02938ec7-b2c3-4131-8ecf-3ad3a8509b41"},"body":{"products"
What I wanted: output
Informacoes [header=Header [messageId=66d22c00-bddc-4ea7-afbd-7c7225fcb914], body=Body
From what I can understand from your question, it looks like Gson might be useful. Gson is a library that allows you to convert between JSON and Java primitives/objects. Here's an example I just wrote:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
}
public static void main(String[] args) {
Gson gson = new Gson();
String json = "{\"value1\":1,\"value2\":\"abc\"}";
BagOfPrimitives obj = gson.fromJson(json, BagOfPrimitives.class);
}
This code converts the json {"value1":1,"value2":"abc"} into an object of the class BagOfPrimitives.
To add Gson to your project, go here, click "Downloads" at the top right, and click "jar". Then follow these instructions to add the jar file to your project. Then you should be able to write import com.google.gson.* at the top of your class and use Gson in your java code.
I have to convert a POJO to JSON object but i am encountering a problem.
My POJO has four variables and their getters and setters.
private String RouteCoord;
private String RouteName;
private String freqArray;
private Double AvgTime;
I have declared a list of objects
List<KPIsStructure> listOfKPIsObjects = new ArrayList<>();
I run a for loop in which i create instances of my POJO class and add them to the already declared list (listOfKPIsObjects)
for (int i=0;i<routes.length;i++){
KPIsStructure innerObject = new KPIsStructure();
innerObject.setRouteCoord(routes[i][1]);
innerObject.setRouteName(routes[i][0]);
innerObject.setAvgTime(AvgTime[i]);
innerObject.setfreqArray(freqArray[i]);
listOfKPIsObjects.add(innerObject);
}
Then there is this another for loop to make a nested JSON Object
for (int i=0;i<listOfKPIsObjects.size();i++){
JSONObject temp = new JSONObject(listOfKPIsObjects.get(i));
processedJson.put("journey_"+(i+1), temp);
}
I return processedJson. The problem is the result is missing one of the variables (String freqArray) of the POJO class.
{"journey_1":{"avgTime":12.283334,"routeCoord":"435,345-789,1011","routeName":"tty-keskustori"},"journey_2":{"avgTime":12.283334,"routeCoord":"123,456-789,1011","routeName":"hervanta-tty"},"journey_3":{"avgTime":12.283334,"routeCoord":"123,456-789,1011","routeName":"kaleva-keskustori"}}
I have tried passing the variables of the class as string and it works and it also shows that the string freqArray is not empty.
String toJson = "{\"RouteName:"+listOfKPIsObjects.get(i).getRouteName()+",RouteCoordinates:"+listOfKPIsObjects.get(i).getRouteCoord()+",AvgTime:"+listOfKPIsObjects.get(i).getAvgTime()+",VisitFrequency:"+listOfKPIsObjects.get(i).getfreqArray()+"}";
Doing it this way takes away the idea of mapping from POJO to JSON object and vice versa and makes it inconvenient.
Any ideas what i might be doing wrong here. I am using org.json.
My json:
{"code":200,"data":[{"xxx":"xxx","yyy":1234,"zzz":"56789"},{...}]}
I need Gson to take the data part in the shape of [{...}] and put it to simple String. But Gson keeps trying to parse it as an array and throws this JsonSyntaxException. Is it possible to get the result as I want it?
Gson fromJson call:
ParsedResponse parsedResponse = gson.fromJson(jsonString, ParsedResponse.class);
ParsedResponse class:
public class ParsedResponse {
#SerializedName("code")
private int code;
#SerializedName("data")
private String data;
private int statusCode;
// getters, setters
}
EDIT:
The system works when I have {...} in data, so why couldn't it work with [{...}]? I just need Gson to take the string [{...}] and put it to String variable.
Basically, no. Just put into Array and then convert to what you need.
Other approach is to see if you can over-ride some parser implementation of GSON.
Or write your own JSON to reflection library. :-).
*** Or, just write your own JSON parsing as your data format might be well-known to you and simply enough. :-)