I am a receiving a JSON object and I need to save the values to my DB. But I'm having an issue figuring out how to retrieve the particular values in the JSON object.
In this case, I want to retrieve the values of 'originationNumber' and 'messageBody'
The response object -
{"originationNumber":"***","destinationNumber":"***","messageKeyword":"KEYWORD_***","messageBody":"Answer ","previousPublishedMessageId":"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0","inboundMessageId":"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb"}
Method to receive message -
public String getReceivedMessages(Messaging receivedMessage) {
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
AmazonSQS sqsClient = AmazonSQSClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.withRegion(String.valueOf(awsRegion)).build();
StringBuilder sb = new StringBuilder();
String queueUrl = "https://sqs.us-east-1.amazonaws.com/1234567/GetReceivedMessages";
List<Message> messages = sqsClient.receiveMessage(new ReceiveMessageRequest(queueUrl)
.withMaxNumberOfMessages(1).withWaitTimeSeconds(20)).getMessages();
for (Message message : messages) {
sb.append(message.getBody());
sqsClient.deleteMessage(queueUrl, message.getReceiptHandle());
}
// Save messages to DB
String userId = connectionRequestRepository.getUserId();
Date date = new Date();
Timestamp now = new Timestamp(date.getTime());
receivedMessage.setUserId(userId);
receivedMessage.setOriginationNumber("");
receivedMessage.setDestinationNumber("***");
receivedMessage.setMessageBody("");
receivedMessage.setMessageType("RECEIVED");
receivedMessage.setCreatedAt(now);
messagingRepository.save(receivedMessage);
System.out.println(sb); <--- Prints response object to console
return sb.toString();
}
You can use jackson library for that.
Solution 1: You can use ObjectMapper as below:
Message Class to map JSON to Java Object:
public class Message {
private String originationNumber;
private String messageBody;
// public getter and setters methods
}
Create Object From JSON String:
Message message = null;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
message = objectMapper.readValue(payload, Message.class);
} catch (JsonProcessingException e) {
// Log Or do some action as per need
}
Here message will have those values. DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES is used here to skip exception as there are other fields also in JSON and not present in Java Class (as we don't need them).
Solution 2: Alternatively you can use JsonNode from same Jackson library and read nodes one by one as below:
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"originationNumber\":\"***\",\"destinationNumber\":\"***\",\"messageKeyword\":\"KEYWORD_***\",\"messageBody\":\"Answer \",\"previousPublishedMessageId\":\"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0\",\"inboundMessageId\":\"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb\"}");
String originationNumber = actualObj.get("originationNumber");
String messageBody = actualObj.get("messageBody");
In this approach you won't need to create Message class.
You can convert the json string into a json object
https://www.javatpoint.com/how-to-convert-string-to-json-object-in-java
String string = "{\"originationNumber\":\"***\",\"destinationNumber\":\"***\",\"messageKeyword\":\"KEYWORD_***\",\"messageBody\":\"Answer \",\"previousPublishedMessageId\":\"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0\",\"inboundMessageId\":\"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb\"}";
JSONObject json = new JSONObject(string);
System.out.println(json.toString());
String destinationNumber = json.getString("destinationNumber");
System.out.println(destinationNumber);
where ur json like
{"originationNumber":"***",
"destinationNumber":"***",
"messageKeyword":"KEYWORD_***",
"messageBody":"Answer","previousPublishedMessageId":"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0",
"inboundMessageId":"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb"
}
it like
"key":Value
i think ur code will be like
receivedMessage.setUserId(userId);
receivedMessage.setOriginationNumber("originationNumber");
receivedMessage.setDestinationNumber("destinationNumber");
receivedMessage.setMessageBody("messageBody");
receivedMessage.setMessageType("RECEIVED");
receivedMessage.setCreatedAt(now);
messagingRepository.save(receivedMessage);
Unable to convert a JSON string which has few elements and an array inside it.
On UI I need to feed the array to bootstrap table.
JSON string:
{
"IsOperationSuccessful": true,
"IsResult": true,
"StatusCode": "OK",
"Response": [{
"PlaylistCreatedBy": "XYZ",
"PlaylistCreatedOn": "10/10/2019 14:10",
"PlaylistDisplayTitle": "blah",
"PlaylistId": 101,
"PlaylistScheduledReleaseTime": "10/10/2019 14:10"
}, {
"PlaylistCreatedBy": "HHJK",
"PlaylistCreatedOn": "10/10/2019 14:10",
"PlaylistDisplayTitle": "blah blah",
"PlaylistId": 102,
"PlaylistScheduledReleaseTime": "10/10/2019 14:10"
}, {
"PlaylistCreatedBy": "HJHJ",
"PlaylistCreatedOn": "10/10/2019 14:10",
"PlaylistDisplayTitle": "UIUI",
"PlaylistId": 103,
"PlaylistScheduledReleaseTime": "10/10/2019 14:10"
}, {
"PlaylistCreatedBy": "KJK",
"PlaylistCreatedOn": "10/10/2019 14:10",
"PlaylistDisplayTitle": "kkj",
"PlaylistId": 104,
"PlaylistScheduledReleaseTime": "10/10/2019 14:10"
}],
"Total": 4
}
The code that I have added so far:
PreRecordedCall morningCallResponse = new PreRecordedCall();
JSONArray playListinfo = null;
String testResponse = "//Json Goes here "
JSONObject finalJson = new JSONObject();
finalJson.put("testResponse", testResponse);
Gson gson = new Gson();
morningCallResponse = gson.fromJson(testResponse,
PreRecordedCall.class);
playListinfo = morningCallResponse.getPreRecordplayListInformation();
One way is to create 2 POJOs (says Response and PreRecordedCall) as follows.
The Response is for the JSON array with key "Response" and the PreRecordedCall is for the whole JSON object. The key is to use List<Response> to store JSON array.
BTW, to follow the naming rule for variables in POJOs with lowerCamelCase, I used #SerializedName for object name mapping.
Class Response
static class Response {
#SerializedName("PlaylistCreatedBy")
private String playlistCreatedBy;
#SerializedName("PlaylistCreatedOn")
private String playlistCreatedOn;
#SerializedName("PlaylistDisplayTitle")
private String playlistDisplayTitle;
#SerializedName("PlaylistId")
private int playlistId;
#SerializedName("PlaylistScheduledReleaseTime")
private String playlistScheduledReleaseTime;
//general getters and setters
}
Class PreRecordedCall
static class PreRecordedCall {
#SerializedName("IsOperationSuccessful")
private Boolean isOperationSuccessful;
#SerializedName("IsResult")
private Boolean isResult;
#SerializedName("StatusCode")
private String statusCode;
#SerializedName("Response")
private List<Response> response;
#SerializedName("Total")
private int total;
//general getters and setters
}
Then you can simply convert the JSON string to pre-defined POJOs as follows:
Gson gson = new Gson();
PreRecordedCall preRecordedCall = gson.fromJson(testResponse, PreRecordedCall.class);
System.out.println(preRecordedCall.getResponse().size());
Console output
4
And if you are using Jackson as your JSON parser, change #SerializedName to #JsonProperty and you can get the same result by following code snippet.
ObjectMapper mapper = new ObjectMapper();
PreRecordedCall preRecordedCall = mapper.readValue(testResponse, PreRecordedCall.class);
System.out.println(preRecordedCall.getResponse().size());
Check if the below code works for you:
String finalJson= "//Json Goes here ";
ObjectMapper objectMapper = new ObjectMapper();
try {
PreRecordedCall morningCallResponse = objectMapper.readValue(json, PreRecordedCall.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
This question already has answers here:
Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice
(4 answers)
Closed 5 years ago.
Good Morning,
I'm relatively new to java and trying to to work through a project, but I'm running into issues. My program uses SQL to build a URL to call a web-service, this service will return the following JSON:
[{
"MmisItemNo": "106552",
"CatalogNo": "UM18840041R",
"ContractOn": "False"
}
]
What I need to do is strip off the "False" or "True" value at the end to do additional logic depending on its result.
I keep getting the following error:
.WebCall -com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of `.LightswitchResponse` out of START_ARRAY token at [Source: (String)"[{"MmisItemNo":"106552","CatalogNo":"UM18840041R","ContractOn":"False"}]"; line: 1, column: 1]
Here is my code currently after the URL is built in the WebCall.java class:
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
ObjectMapper mapper = new ObjectMapper();
LightswitchResponse lightswitchResponse = mapper.readValue(response.toString(), LightswitchResponse.class);
System.out.println(lightswitchResponse.ContractOn);
In my second class the code is as follows:
public class LightswitchResponse {
String MmisItemNo;
String CatalogNo;
boolean ContractOn;
public String getMmisItemNo() {
return MmisItemNo;
}
public void setMmisItemNo(String mmisItemNo) {
MmisItemNo = mmisItemNo;
}
public String getCatalogNo() {
return CatalogNo;
}
public void setCatalogNo(String catalogNo) {
CatalogNo = catalogNo;
}
public boolean ContractOn() {
return ContractOn;
}
public void setContractOn(boolean contractOn) {
ContractOn = contractOn;
}
}
Any ideas on what might be going wrong? I feel like it might have something to do with the [] on the JSON response, but not 100% sure.
You are right it is because of the [] on the JSON response. This means that the JSON object that is being returned is an array of objects.
Hence to get Jackson to map it correctly you should be doing this:
LightswitchResponse[] lightswitchResponses =
mapper.readValue(response.toString(), LightswitchResponse[].class);
You can then read the first element off this to get your desired LightSwitchResponse object:
LightswitchResponse lightswitchResponse = lightswitchResponses[0];
I am trying to use org.json.JSONObject to build the following target json string:
{"und":[{"value":"some#one.com"}]}
Here is my code:
JSONObject und = new JSONObject();
und.accumulate("und", new JSONObject().put("value", "some#one.com"));
System.out.println( und.toString() );
But it produces the following:
{"und":{"value":"some#one.com"}}
How can I produce the target json string?
Thanks and regards.
EDIT
Thanks to SLaks's input, here is the code that produces the target string:
JSONObject und = new JSONObject();
JSONArray arr = new JSONArray();
und.put("und", arr);
arr.put(new JSONObject().put("value", "some#one.com"));
System.out.println( und.toString() );
You might want to take a look at Jackson, it's one of the most efficient and supported JSON libraries available on Java.
If you are familiar with unmarshalling/deserialization, you can turn an POJO into json and vise versa.
#JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class SomeBean {
Und[] und;
// TODO: Getters and setters
public static Und class {
public String value;
// TODO: Getters and setters
}
}
If you are directly parsing a JSON string or file, you can use the ObjectMapper class
SomeBean someBean = new ObjectMapper().readValue("input goes here", SomeBean.class);
// If you want just a string you can pass in the String class
String json = new ObjectMapper().readValue("input", String.class);
If the JSON is coming from a web service, check out Spring's restTemplate, super easy to work with.
RestTemplate restTemplate = new RestTemplate();
SomeBean someBean = restTemplate.getForEntity("URI goes here", SomeBean.class);
String json = restTemplate.getForEntity("URI goes here", String.class);
I have String variable called jsonString:
{"phonetype":"N95","cat":"WP"}
Now I want to convert it into JSON Object. I searched more on Google but didn't get any expected answers!
Using org.json library:
try {
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
Log.d("Error", err.toString());
}
To anyone still looking for an answer:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
You can use google-gson. Details:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
Another example for Gson:
Gson is easy to learn and implement, you need to know is the following two methods:
-> toJson() – convert java object to JSON format
-> fromJson() – convert JSON into java object
import com.google.gson.Gson;
public class TestObjectToJson {
private int data1 = 100;
private String data2 = "hello";
public static void main(String[] args) {
TestObjectToJson obj = new TestObjectToJson();
Gson gson = new Gson();
//convert java object to JSON format
String json = gson.toJson(obj);
System.out.println(json);
}
}
Output
{"data1":100,"data2":"hello"}
Resources:
Google Gson Project Home Page
Gson User Guide
Example
There are various Java JSON serializers and deserializers linked from the JSON home page.
As of this writing, there are these 22:
JSON-java.
JSONUtil.
jsonp.
Json-lib.
Stringtree.
SOJO.
json-taglib.
Flexjson.
Argo.
jsonij.
fastjson.
mjson.
jjson.
json-simple.
json-io.
google-gson.
FOSS Nova JSON.
Corn CONVERTER.
Apache johnzon.
Genson.
cookjson.
progbase.
...but of course the list can change.
Java 7 solution
import javax.json.*;
...
String TEXT;
JsonObject body = Json.createReader(new StringReader(TEXT)).readObject()
;
To convert String into JSONObject you just need to pass the String instance into Constructor of JSONObject.
Eg:
JSONObject jsonObj = new JSONObject("your string");
String to JSON using Jackson with com.fasterxml.jackson.databind:
Assuming your json-string represents as this: jsonString = {"phonetype":"N95","cat":"WP"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Simple code exmpl
*/
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
String phoneType = node.get("phonetype").asText();
String cat = node.get("cat").asText();
I like to use google-gson for this, and it's precisely because I don't need to work with JSONObject directly.
In that case I'd have a class that will correspond to the properties of your JSON Object
class Phone {
public String phonetype;
public String cat;
}
...
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Gson gson = new Gson();
Phone fooFromJson = gson.fromJson(jsonString, Phone.class);
...
However, I think your question is more like, How do I endup with an actual JSONObject object from a JSON String.
I was looking at the google-json api and couldn't find anything as straight forward as
org.json's api which is probably what you want to be using if you're so strongly in need of using a barebones JSONObject.
http://www.json.org/javadoc/org/json/JSONObject.html
With org.json.JSONObject (another completely different API) If you want to do something like...
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
System.out.println(jsonObject.getString("phonetype"));
I think the beauty of google-gson is that you don't need to deal with JSONObject. You just grab json, pass the class to want to deserialize into, and your class attributes will be matched to the JSON, but then again, everyone has their own requirements, maybe you can't afford the luxury to have pre-mapped classes on the deserializing side because things might be too dynamic on the JSON Generating side. In that case just use json.org.
Those who didn't find solution from posted answers because of deprecation issues, you can use JsonParser from com.google.gson.
Example:
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(jsonObject.get("phonetype"));
System.out.println(jsonObject.get("cat"));
you must import org.json
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
} catch (JSONException e) {
e.printStackTrace();
}
Codehaus Jackson - I have been this awesome API since 2012 for my RESTful webservice and JUnit tests. With their API, you can:
(1) Convert JSON String to Java bean
public static String beanToJSONString(Object myJavaBean) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.writeValueAsString(myJavaBean);
}
(2) Convert JSON String to JSON object (JsonNode)
public static JsonNode stringToJSONObject(String jsonString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readTree(jsonString);
}
//Example:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JsonNode jsonNode = stringToJSONObject(jsonString);
Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());
(3) Convert Java bean to JSON String
public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readValue(JSONString, beanClass);
}
REFS:
Codehaus Jackson
JsonNode API - How to use, navigate, parse and evaluate values from a JsonNode object
Tutorial - Simple tutorial how to use Jackson to convert JSON string to JsonNode
Converting String to Json Object by using org.json.simple.JSONObject
private static JSONObject createJSONObject(String jsonString){
JSONObject jsonObject=new JSONObject();
JSONParser jsonParser=new JSONParser();
if ((jsonString != null) && !(jsonString.isEmpty())) {
try {
jsonObject=(JSONObject) jsonParser.parse(jsonString);
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}
return jsonObject;
}
To convert a string to json and the sting is like json. {"phonetype":"N95","cat":"WP"}
String Data=response.getEntity().getText().toString(); // reading the string value
JSONObject json = (JSONObject) new JSONParser().parse(Data);
String x=(String) json.get("phonetype");
System.out.println("Check Data"+x);
String y=(String) json.get("cat");
System.out.println("Check Data"+y);
Use JsonNode of fasterxml for the Generic Json Parsing. It internally creates a Map of key value for all the inputs.
Example:
private void test(#RequestBody JsonNode node)
input String :
{"a":"b","c":"d"}
If you are using http://json-lib.sourceforge.net
(net.sf.json.JSONObject)
it is pretty easy:
String myJsonString;
JSONObject json = JSONObject.fromObject(myJsonString);
or
JSONObject json = JSONSerializer.toJSON(myJsonString);
get the values then with
json.getString(param) or/and json.getInt(param) and so on.
No need to use any external library.
You can use this class instead :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
To convert your JSON string to hashmap use this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(
For setting json single object to list
ie
"locations":{
}
in to List<Location>
use
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
jackson.mapper-asl-1.9.7.jar
NOTE that GSON with deserializing an interface will result in exception like below.
"java.lang.RuntimeException: Unable to invoke no-args constructor for interface XXX. Register an InstanceCreator with Gson for this type may fix this problem."
While deserialize; GSON don't know which object has to be intantiated for that interface.
This is resolved somehow here.
However FlexJSON has this solution inherently. while serialize time it is adding class name as part of json like below.
{
"HTTPStatus": "OK",
"class": "com.XXX.YYY.HTTPViewResponse",
"code": null,
"outputContext": {
"class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
"eligible": true
}
}
So JSON will be cumber some; but you don't need write InstanceCreator which is required in GSON.
Using org.json
If you have a String containing JSON format text, then you can get JSON Object by following steps:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
Now to access the phonetype
Sysout.out.println(jsonObject.getString("phonetype"));
Better Go with more simpler way by using org.json lib. Just do a very simple approach as below:
JSONObject obj = new JSONObject();
obj.put("phonetype", "N95");
obj.put("cat", "WP");
Now obj is your converted JSONObject form of your respective String. This is in case if you have name-value pairs.
For a string you can directly pass to the constructor of JSONObject. If it'll be a valid json String, then okay otherwise it'll throw an exception.