I am working on a jersey - java project where I have to get the json data in string format and parse each data separately. I am able to get the response in string using post method. When I try to use JSON lib to parse the string data class not found exception is produced. I want the returned string to be split up. Below is my json.
{
"startdate": "11/11/11",
"enddate": "12/12/12",
"operation_name": "task1",
"user_id": "user1",
"operation_key": ["KKMM-025", "SFF-025", "TTR-022"]
}
Resource method
#POST
#Path("OpertaionDetails")
#Consumes({MediaType.APPLICATION_JSON , MediaType.APPLICATION_XML})
public Response CreateOperations(String incoming_data) throws Exception
{
try
{
JSONParser parse = new JSONParser(); // class not found exceptin i have added the lib properly its working fine when it is used in main method of java.
JSONObject jobj = (JSONObject)parse.parse(incoming_data);
JSONObject Jstart_date = (JSONObject) jobj.get("startdate");
// this data to be paresed
System.out.print("incomingData"+incoming_data);
}
catch(Exception e)
{
e.printStackTrace();
}
return Response.ok(incoming_data).build();
}
I'm trying to build an app for a course that extracts news data from a particular JSON and displays in on the screen. I logged my errors, and it's rejecting the way I'm extracting my data. Here's a sample of the json layout:
"response": {
"status": "ok",
"userTier": "developer",
"total": 2050598,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 205060,
"orderBy": "newest",
"results": [
{
"id": "technology\/2018\/jul\/26\/facebook-stock-price-falling-what-does-it-mean-analysis",
"type": "article",
"sectionId": "technology",
"sectionName": "Technology",
"webPublicationDate": "2018-07-26T19:12:07Z",
"webTitle": "Does Facebook's plummeting stock spell disaster for the social network?",
"webUrl": "https:\/\/www.theguardian.com\/technology\/2018\/jul\/26\/facebook-stock-price-falling-what-does-it-mean-analysis",
"apiUrl": "https:\/\/content.guardianapis.com\/technology\/2018\/jul\/26\/facebook-stock-price-falling-what-does-it-mean-analysis",
"isHosted": false,
"pillarId": "pillar\/news",
"pillarName": "News"
},
and here's my resulting code that it's not liking:
// Returns News List from JSON Response
private static List<News> extractFeatureFromJson(String newsJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
// Create an empty ArrayList that we can add news stories to
List<News> news = new ArrayList<>();
// Try to parse the JSON response string. Errors will be sent to log.
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(newsJSON);
// Extract the JSONArray associated with the key called "response",
JSONArray newsArray = baseJsonResponse.getJSONArray("response");
// For each article in the newsArray, create an {#link News} object
for (int i = 0; i < newsArray.length(); i++) {
// Get a single article at position i within the list of articles
JSONObject currentNews = newsArray.getJSONObject(i);
// Extract results for news story
JSONObject results = currentNews.getJSONObject("results");
// Extract the value for the key called webTitle
String webTitle = results.getString("webTitle");
// Extract the value for the key called "sectionName"
String sectionName = results.getString("sectionName");
// Extract the value for the key called "webPublicationDate"
long webPublicationDate = results.getLong("webPublicationDate");
// Extract the value for the key called "webUrl"
String webUrl = results.getString("webUrl");
// Create a new {#link Earthquake} object with the title, category, date,
// and url from the JSON response.
News news1 = new News(webTitle, sectionName, webPublicationDate, webUrl);
// Add the new {#link News} to the list of articles.
news.add(news1);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the Guardian JSON results", e);
}
// Return the list of articles
return news;
}
I don't understand what the heck I'm doing wrong, because I feel like I'm replicating the data, right? Anyway, I have no idea.
It's also throwing me errors for my Loader:
public class NewsLoader extends AsyncTaskLoader<List<News>> {
// Tag for Log Messages
private static final String LOG_TAG = NewsLoader.class.getName();
// Query URL
private String mUrl;
/**
* Constructs a new {#link NewsLoader}.
* #param context of the activity
* #param url to load data from
*/
public NewsLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
//Background Thread
public List<News> loadInBackground() {
if (mUrl == null) {
return null;
}
// Perform the network request, parse the response, and extract news articles.
List<News> news = QueryUtils.fetchNewsData(mUrl);
return news;
} }
Errors thrown:
at com.example.android.newsapp.QueryUtils.extractFeatureFromJson(QueryUtils.java:135)
at com.example.android.newsapp.QueryUtils.fetchNewsData(QueryUtils.java:44)
at com.example.android.newsapp.NewsLoader.loadInBackground(NewsLoader.java:42)
at com.example.android.newsapp.NewsLoader.loadInBackground(NewsLoader.java:11)
1) The "response" is a JSON Object, not JSON Array.
2) The "results" is a JSON Array, not a JSON Object.
3) The webPublicationDate type is Sting not long.
In order to parse the Json correctly try this:
// Returns News List from JSON Response
private static List<News> extractFeatureFromJson(String newsJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
// Create an empty ArrayList that we can add news stories to
List<News> news = new ArrayList<>();
// Try to parse the JSON response string. Errors will be sent to log.
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(newsJSON);
// Extract the JSONArray associated with the key called "response",
JSONObject resultObject = baseJsonResponse.getJSONObject("response");
// Extract JSON array of resultObject
JSONArray newsArray = resultObject.getJSONArray("results");
// For each article in the resultObject, create an {#link News} object
for (int i = 0; i < newsArray.length(); i++) {
// Get a single article at position i within the list of articles
JSONObject currentNews = newsArray.getJSONObject(i);
// Extract the value for the key called webTitle
String webTitle = currentNews.getString("webTitle");
// Extract the value for the key called "sectionName"
String sectionName = currentNews.getString("sectionName");
// Extract the value for the key called "webPublicationDate"
String webPublicationDate = currentNews.getString("webPublicationDate");
// Extract the value for the key called "webUrl"
String webUrl = currentNews.getString("webUrl");
// Create a new {#link Earthquake} object with the title, category, date,
// and url from the JSON response.
// CHANGE YOUR NEWS CLASS' webPublicationDate FIELD TO STRING OR
// DON'T FORGET TO CONVERT IT TO LONG!!!!
News news1 = new News(webTitle, sectionName, webPublicationDate, webUrl);
// Add the new {#link News} to the list of articles.
news.add(news1);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the Guardian JSON results", e);
}
// Return the list of articles
return news;
}
Hope I could help you!
Best regards,
Csongor
I am using the below code to convert json to xml of multiple XML files with different JSON structures.
String toXmlRequest = fullRequest.toString();
JSONObject jsonObj = new JSONObject(toXmlRequest);
String XmlRequest = XML.toString(jsonObj);
System.out.println(XmlRequest);
Input
{
"EnrollmentRequest":
{
"data":
{
"commonDataContext":
{
"requestId": "ADA12131",
"clientId": "ABCDEF",
"timestamp":"2013-12-13T11:10:00.715-05:00"
},
"cardNumber" : "123456789012345" ,
"firstName" : "John" ,
"lastName" : "Smith" ,
"email" : "JohnSmith#g.com" ,
"enrollStatus" : "E" ,
"pathEnroll" : "NewAcct",
"cardSavedIndicator" : "Y"
}
}
}
Output
<EnrollmentRequest>
<data>
<firstName>John</firstName>
<lastName>Smith</lastName>
<commonDataContext>
<clientId>ABCDEF</clientId>
<requestId>ADA12131</requestId>
<timestamp>2013-12-13T11:10:00.715-05:00</timestamp>
</commonDataContext>
<pathEnroll>NewAcct</pathEnroll>
<enrollStatus>E</enrollStatus>
<cardSavedIndicator>Y</cardSavedIndicator>
<cardNumber>123456789012345</cardNumber>
<email>JohnSmith#g.com</email>
</data>
</EnrollmentRequest>
The sequence of the output is getting changed. It is not able to keep the actual sequence. Is there any way this can be kept intact.
This is not possible using org.json.JSONObject directly. The reason is that JSONObject uses an internal store of type HashMap. HashMap does not preserve insertion order
It would be possible with a LinkedHashMap, however it does not appear possible to configure JSONObject to use one.
/**
* Construct an empty JSONObject.
*/
public JSONObject() {
this.map = new HashMap<String, Object>();
}
An alternative would be to read using a library that does preserve order, e.g. Jackson....
ObjectMapper mapper = new ObjectMapper();
JsonNode jackson = mapper.readTree(fullRequest);
and then feed that into XML
String xmlRequest = XML.toString(new JSONAdapter(jackson));
with the necessary type adaption to make the Jackson object look like a org.json.JSONObject. Incomplete example below:
private static class JSONAdapter extends JSONObject {
private JsonNode jackson;
public JSONAdapter(JsonNode jackson) {
this.jackson = jackson;
}
#Override
public Iterator<String> keys() {
return jackson.fieldNames();
}
#Override
public Object opt(String key) {
return get(key);
}
#Override
public Object get(String key) throws JSONException {
JsonNode nested = jackson.get(key);
if (nested.isObject()) {
return new JSONAdapter(nested);
} else if (nested.isTextual()) {
return nested.asText();
} else if (nested.isNumber()) {
return nested.asDouble();
} else if (nested.isBoolean()) {
return nested.asBoolean();
}
return null;
}
}
Output
<EnrollmentRequest>
<data>
<commonDataContext>
<requestId>ADA12131</requestId>
<clientId>ABCDEF</clientId>
<timestamp>2013-12-13T11:10:00.715-05:00</timestamp>
</commonDataContext>
<cardNumber>123456789012345</cardNumber>
<firstName>John</firstName>
<lastName>Smith</lastName>
<email>JohnSmith#g.com</email>
<enrollStatus>E</enrollStatus>
<pathEnroll>NewAcct</pathEnroll>
<cardSavedIndicator>Y</cardSavedIndicator>
</data>
</EnrollmentRequest>
For embedded json arrays, you need to apply one more condition to check if it array and return it as json array.
if(nested.isArray()) {
JSONArray arr = new JSONArray();
for(JsonNode value : nested){
arr.put(value.asText());
}
return arr;
}
JSONObject myObject = new JSONObject();
try {
testVoList.add(new TestVO(1L, "HAI1"));
testVoList.add(new TestVO(2L, "HAI2"));
myObject.put("name", testVoList);
} catch (JSONException ex) {
}
String s = URLEncoder.encode(myObject.toString(), "UTF-8");
URL url = new URL("urlName/"+s);
CODE IN WEBSERVICE TO RECIEVE DATA:
#POST
#Path("/urlName/{test}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String saveSurveyresponseData(#PathParam("test") JSONObject responseData)
{
JSONArray.fromObject(responseData.getString("name")).get(0);
return "HAI";
}
Here i am getting test.TestVO#c2ea3f(Hashcode) for
JSONArray.fromObject(responseData.getString("name")).get(0);
How can I access my list of objects values in my webservice.
Can you suggest me a solution?
I believe the following statement:
JSONArray.fromObject(responseData.getString("name")).get(0);
is returning the list. So simply assign it to a list reference as mentioned here:
List<TestVO> listOfTestVO = JSONArray.fromObject(responseData.getString("name")).get(0);
Now simply get the elements as:
listOfTestVO.get(1);
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.