I have the following result class whose object is to be returned as JSON.
public class Result {
public String objectid;
public String dtype;
public String type;
public String name;
public String description;
public Result() {
this.objectid = "";
this.dtype= "";
this.type="";
this.name= "";
this.description = "";
}
public String getObjectid() {
return objectid;
}
public void setObjectid(String s) {
this.objectid = s;
}
public String getDtype() {
return dtype;
}
public void setDtype(String s) {
this.dtype= s;
}
public String getType() {
return type;
}
public void setType(String s) {
this.type = s;
}
public String getName() {
return name;
}
public void setName(String s) {
this.name = s;
}
public String getDescription() {
return description;
}
public void setDescription(String s) {
this.description = s;
}
}
I have a configuration json which is read my the main .java and returned as json as HTTP RESPONSE. It is as below:
{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name" : "test",
"description" : "test" // removed
},
{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name" : "test",
"description" : "test"
}
Main .java
Using Gson, it reads the configuration.json file and has to return a json.
My code:
Gson g = new Gson();
Result r = g.fromJson(res.toString(), Result.class);
where res.toString() gets me the configuration.json file content as string.
My problem:
I am experiencing the following exception:
Exception com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 7 column 3
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 7 column 3
Any pointers?
If this is the actual json: You have an extra comma here and a spelling error. The error says you have bad json syntax. So this is probably one of the first places to look.
{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name " : "test",
"description" : "test", //delete this comma
},
{
"objectid" : "test",
"dtyoe" : "test", // spelling error
"type" : "test",
"name " : "test",
"description" : "test"
}
You also seem to be parsing two objects and telling gson you want one result object from it.
Consider either parsing the objects separately or tell gson you want a result array Back
use
catch(JsonSyntaxException e)
instead of
catch(MalformedJsonException e)
because MalformedJsonException is some internal exception while JsonSyntaxException is the one that actually get thrown. here is a code snippet
String response="Something";
JsonElement my_json;
try {
my_json=jsonParser.parse(response);
} catch(JsonSyntaxException e) {
e.printStackTrace();
JsonReader reader = new JsonReader(new StringReader(response));
reader.setLenient(true);
my_json=jsonParser.parse(reader);
}
You have two objects but getting one object from GSON. either you should use below format of JSON string to get Result object from this JSON string.
{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name" : "test",
"description" : "test"
}
Second option :-
You will have to change JSON string format. you will have to change it in JSON array and get ArrayList of this object, After that, we can get Result object using array list index.new JSON string would be like this.
{"resultArray":[{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name" : "test",
"description" : "test"
},
{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name" : "test",
"description" : "test"
}]}
And java code to fetch Result Object.
Gson g = new Gson();
ResultList r = g.fromJson(res.toString(), ResultList.class);
ArrayList<Result> resultList = r.getResultList();
for(int x=0 ;x<resultList.size();x++){
Result result = resultList.get(x);
}
ResultList Model is:-
public class ResultList {
#SerializedName("resultArray")
public ArrayList<Result> resultList;
public getResultList(){
return resultList;
}
}
#Note: - Result.java would be used same as given above.
My Issue was the JSON string was too long for the parser to handle. I shortened the string and it worked.
Related
{
"DistributionOrderId" : "Dist_id_1",
"oLPN":
{
"Allocation":
{
"AID": "12345"
},
"Allocation":
{
"AID": "123456" ,
"SerialNbr": "SRL001",
"BatchNbr": "LOT001"
"RevisionNbr": "RVNBR1"
}
},
"oLPN":
{
"Allocation":
{
"AID": "12123"
}
"Allocation":
{
"AID": "12124"
}
}
}
I have a JSON request passed from the vendor, How to store the values as Java POJO and use them further?
Edit : Added attributes to JSON
As you aren't using the usual camel case conventions common in jackson databinding I would suggest defining a java object with the appropriate annotations. The object is not currently valid json. If for example the json looks like this:
{
"DistributionOrderId" : "Dist_id_1",
"oLPN": [ ... ]
}
Where each oLPN in the array is an object like this:
{
"Allocation": [{ "AID": ... }, { "AID": ... }, ... ]
}
You can write a class for distribution orders
public class DistributionOrder {
#JsonProperty("DistributionOrderId") private String id;
#JsonProperty("oLPN") private List<OLPN> olpn;
// getters and setters
}
Then another for the OLPN object
public class OLPN {
#JsonProperty("Allocation") private String allocation;
#JsonProperty("AID") private String aid;
// getters and setters
}
Then you can use an object mapper as appropriate. For example
ObjectMapper mapper = ... // get your object mapper from somewhere
DistributionOrder distributionOrder = mapper.readValue(raw, DistributionOrder.class);
See also object mapper javadoc
json key can't repeat, and the repeat key with value will be discard.
i have format your json text, may be it is like following expression:
{
"DistributionOrderId" : "Dist_id_1",
"oLPN":
[
{
"Allocation":
[
{
"AID": "123456" ,
"SerialNbr": "SRL001",
"BatchNbr": "LOT001",
"RevisionNbr": "RVNBR1"
},
{
"AID": "12345"
}
]
},
{
"Allocation":
[
{
"AID": "12123"
},
{
"AID": "12124"
}
]
}
]
}
and this struct match the java object is
class DistributionOrder{
#JsonProperty("DistributionOrderId")
String distributionOrderId;
List<OLPN> oLPN;
}
class OLPN {
#JsonProperty("Allocation")
List<Allocation> allocation;
}
class Allocation{
String AID;
#JsonProperty("SerialNbr")
String serialNbr;
#JsonProperty("BatchNbr")
String batchNbr;
#JsonProperty("RevisionNbr")
String revisionNbr;
}
I have a Json array that I parse to GSON. It has the following content:
[
{
"type": "way",
"id": 70215497,
"nodes": [
838418570,
838418571
]
},
{
"type": "way",
"id": 70215500,
"nodes": [
838418548,
838418626
]
}
]
I tried to parse it using the following sample of code:
while (jsonReader.hasNext()){
Element type = gson.fromJson(jsonReader, Element.class);
if (type.GetType().contentEquals("way")) {
Way way = gson.fromJson(jsonReader, Way.class);
System.out.println(way.GetId());
}
}
Where Element is simply
public class Element {
private String type;
public String GetType() {
return type;
}
}
and Way is
public class Way {
private long id;
private String type;
List<Long> nodes;
public long GetId() {
return id;
}
}
Now for some reason only 70215500 will print out. And this happens for a few other elements in the real code. Why is that ?
Edit: It basically only reads 1/2 object. Why?
You do not need to read Element class first and after that Way class. Read Way and check it's type:
try (JsonReader jsonReader = new JsonReader(new FileReader(jsonFile))) {
jsonReader.beginArray();
while (jsonReader.hasNext()) {
Way way = gson.fromJson(jsonReader, Way.class);
if (way.getType().contentEquals("way")) {
System.out.println(way.getId());
}
}
}
Above code should print all ids.
I am writing a REST client using RestTemplate and GSON.
Below is sample of my JSON response
{
"value": [
{
"properties": {
"vmId": "f7f953fb-d853-4373-b564-",
"hardwareProfile": {
"vmSize": "Standard_D2"
},
},
"name": "A",
"Id": ""
},
{
"properties": {
"vmId": "f7f953fb-d853-4373-b564-",
"hardwareProfile": {
"vmSize": "Standard_D2"
},
},
"name": "B",
"Id": ""
},
{
"properties": {
"vmId": "f7f953fb-d853-4373-b564-",
"hardwareProfile": {
"vmSize": "Standard_D2"
},
},
"name": "C",
"Id": ""
}
]
}
What I want to is that I want to get only the values for the property --> "name"
So I created a simple POJO that has only name as the member field.
public class VMNames {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and I am trying to use the GSON like this to get a array of this POJO. Here, the response is my JSON response object.
Gson gson = new Gson();
VMNames[] vmNamesArray = gson.fromJson(response.getBody(), VMNames[].class);
System.out.println(vmNamesArray.length);
But when I do this, I get an error i.e. as below:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Please note that I don't want to create a POJO that has exactly same structure as my JSON object because I want to get only one attribute out of my JSON object. I am hoping that I won't have to really create a POJO with the same structure as my JSON response because, in reality, it's a huge response and I don't control it, so it can also change tomorrow.
Can you try this:
public class VMNames {
#SerializedName("name")
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Type collectionType = new TypeToken<Collection<VMNames>>(){}.getType();
Collection<VMNames> vmNamesArray = gson.fromJson(response.getBody(), collectionType);
System.out.println(vmNamesArray.length);
or try:
VMNames[] vmNamesArray = gson.fromJson(response.getBody(), VMNames[].class);
So I could get this done. Posting the answer to this so that someone can be benefited tomorrow :)
First thing, i stopped using GSON and started using JSON.
And below is the code that helped.
RestTemplate restTemplate = new RestTemplate();
response = (ResponseEntity<String>) restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
JSONObject jsonObj = new JSONObject(response.getBody().toString());
JSONArray c = jsonObj.getJSONArray("value");
for (int i = 0; i < c.length(); i++) {
JSONObject obj = c.getJSONObject(i);
String VMName = obj.getString("name");
VMNames vmnames = new VMNames();
vmnames.setName(VMName);
vmNames.add(vmnames);
}
return vmNames;
And i get a list of all the value against the attribute name in form of a json array.
I would like to get value from JSON. I am using Google Gson.
Here is my Json format :
{
"idContact" : 1,
"message" : "myMessage",
"date" : "07/03/2016 21:58:38",
"Client" : {
"idClient" : 122,
"lastName" : "LASTNAME",
"firstName" : "FIRSTNAME",
"phone" : "060000"
}
}
I can get values from message and date by using :
Gson gson = new GsonBuilder().create();
MyClass myClass = gson.fromJson(jsonMessage, MyClass.class);
System.out.println("message: "+smsJson.getMessage());
But I can't have values for my Client. When I do System.out.println("message: "+smsJson.getClient().getId()); I have null pointer exception.
MyClass is :
public class MyClass {
String message;
String date;
Contact contact;
Client client;
}
Thanks
I need to parse the following JSON in Java using Gson Library. Can anyone help me as I am new to JSON?
alarmEvent = {
"version" : "1.0"
"type" : "ALARM",
"nodeId" : "",
"timeStamp" : "",
"params" : {
"paramId" : "",
"alarmType" : "",
"category" : "",
"source" : "",
"parameter": "",
"alarm" : "",
"alias" : "",
"duration" : ""
}
}
You can create an AlarmEvent class, containing a member for each field you expect to see in the JSON object. For example:
class AlarmEvent {
private String version;
private String type;
....
}
Then, you can instantiate an object of this type as follows:
AlarmEvent a = new Gson().fromJson(json, AlarmEvent.class);
You can now access the fields directly as a.version, a.type, etc.
JsonObject jobj = new Gson().fromJson(json, JsonObject.class);