Can not convert json string to object - java

I'm constructiong a JSONObject in my javascript and then sending it as a string to my servlet using this code:
insertDtls = function() {
var jsonObj = [];
jsonObj.push({location: this.location()});
jsonObj.push({value: this.value()});
jsonObj.push({coverage: this.coverage()});
jsonObj.push({validPeriod: this.collateralValidPer()});
jsonObj.push({description: this.description()});
var b = JSON.stringify(jsonObj);
console.log(b.toString());
$.ajax({
url:"/HDSWFHub/AppProxy",
type: 'GET',
data: $.extend({WrJOB: "insertDtls", mainData: b}, tJS.getCommonPostData()),
dataType: "json",
success: function(responseText, status, xhr){
updateViewModel(responseText);
},
error: function(jqXHR, textStatus, error){
tJS.manageError(jqXHR);
}
});
},
The string looks like:
[{"location":"Boston"},{"value":"5"},{"coverage":"15"},{"validPeriod":"08/05/2013"},{"description":"test description"}] and the servlet receives it without a problem.
Then I'm getting this in my servlet:
String step = request.getParameter("mainData");
JSONObject jsonObj = new JSONObject();
final JSONObject obj = new JSONObject();
System.out.println(step);
try {
obj.put("viewModel", "index");
obj.put("WrSESSIONTICKET", sessionTicket);
response.getWriter().print(obj.toString());
} catch (final Exception e) {
logException(request, response, e, true);
}
I'm trying to convert the JSON string back to object in the servlet in order to be able to loop trough the items, or to get the needed one. The library I'm using is org.json
I have tired:
JSONObject jsonObj = new JSONObject(step);
Without any success. Just got this error:
Unhandled exception type JSONException
I don't know what is happening. Maybe I'm too tired already. I'm sure that I'm missing something really small, but I'm unable to spot it.
I know that it has been asked hundreds of times. I know that I will get tons of downvotes, but I was unable to find an answer for my issue.

I tried the string you posted in your comment and it works fine. Here is the full code:
import org.json.JSONArray;
import org.json.JSONException;
public class jsonArray {
public static void main(String[] args) {
String text = "[{\"location\":\"Boston\"},{\"value\":\"5\"},{\"coverage\":\"15\"},{\"validPeriod\":\"08/05/2013\"},{\"description\":\"test description\"}]";
try {
JSONArray jsonArray = new JSONArray(text);
System.out.println(jsonArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
p.s. I am using org.json-20120521.jar library

Here your json String is converted to JSONObject .
In your case its not happening because [] brackets denotes Array. so first it is Array and then {} JSONObject in case of your String.
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
static String str = "[{\"location\":\"Boston\"},{\"value\":\"5\"},{\"coverage\":\"15\"},{\"validPeriod\":\"08/05/2013\"},{\"description\":\"test description\"}]";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JSONArray jsonArr = new JSONArray(str);
System.out.println("JSON ARRAY IS : ");
System.out.println(jsonArr.toString());
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println();
System.out.println(i+" JSON OBJECT IS : ");
System.out.println(jsonObj.toString());
}
} catch (org.json.JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
JSON ARRAY IS :
[{"location":"Boston"},{"value":"5"},{"coverage":"15"},{"validPeriod":"08/05/2013"},{"description":"test description"}]
0 JSON OBJECT IS :
{"location":"Boston"}
1 JSON OBJECT IS :
{"value":"5"}
2 JSON OBJECT IS :
{"coverage":"15"}
3 JSON OBJECT IS :
{"validPeriod":"08/05/2013"}
4 JSON OBJECT IS :
{"description":"test description"}

Related

Java "string" is not a JSONObject error when I try to parse string to JSON [duplicate]

I am now currently using a weather API from http://wiki.swarma.net/index.php?title=%E5%BD%A9%E4%BA%91%E5%A4%A9%E6%B0%94API/v2 and wished to convert the JSONObject into printable Strings. However, when I am working on the following code, two errors occurred:
public class getApi {
private static final String WEATHER_MAP_URL = "https://api.caiyunapp.com/v2/TAkhjf8d1nlSlspN/121.6544,25.1552/realtime.json";
private static final String WEATHER_TEST_API = "TAkhjf8d1nlSlspN";
public static JSONObject getWeatherJson() {
try {
URL url = new URL( WEATHER_MAP_URL );
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty( "x-api-key", WEATHER_TEST_API );
BufferedReader reader = new BufferedReader(
new InputStreamReader( connection.getInputStream()) );
StringBuffer json = new StringBuffer( 1024 );
String tmp;
while( (tmp = reader.readLine()) != null )
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject( json.toString() );
if(data.getJSONObject("status").toString() != "ok" ) {
return null;
}
return data;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
public static void main( String[] args ) {
JSONObject WeatherJson = getWeatherJson();
try {
JSONArray details = WeatherJson.getJSONObject("result").getJSONObject("hourly").
getJSONArray("skycon");
System.out.println(details.getJSONObject(0).getJSONObject("value").toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The JSONObject structure, which is also shown in the link above, is like this:
{
"status":"ok",
"lang":"zh_CN",
"server_time":1443418212,
"tzshift":28800,
"location":[
25.1552, //latitude
121.6544 //longitude
],
"unit":"metric",
"result":{
"status":"ok",
"hourly":{
"status":"ok",
"skycon":[
{
"value":"Rain",
"datetime":"2015-09-28 13:00"
},
{
...
}]
}
}
}
The error occurred:
org.json.JSONException: JSONObject["status"] is not a JSONObject.
at org.json.JSONObject.getJSONObject(JSONObject.java:557)
at getApi.getWeatherJson(getApi.java:34)
at getApi.main(getApi.java:45)
Exception in thread "main" java.lang.NullPointerException
at getApi.main(getApi.java:47)
I have looked at similar posts on the topic is not a JSONObject Exception but found that none of them can help me. I suspect that something is wrong with requesting the data, so actually, getWeatherJson() returns a null object and results in the NullPointerException and JSONObjectException.
Can anyone help me with the code?
According to the getJSONObject() Javadoc, this method will throw an exception if the returned object isn't a true JSON object, which it isn't because "status" is a string. As such, try using data.getString("status").
The status field in the JSON document you have posted is not an object. In JSON, objects are enclosed in with {} brackets. The result node however, is a nested object which holds the status key/value pair. Try the following:
JSONObject data = new JSONObject(json.toString());
if(data.getJSONObject("result").get("status").toString() != "ok" ) {
return null;
}

Reading a json and csv dynamically with the same name

Reading first json with this name TestNameUS.json from the amazon S3Client directory and getting the sql from it and then hitting the db using the sql and matching the result with other Amazon S3 output directory containing the TestNameUS.csv with the same name as the name of the first json.
My code is below. It gives me the sql.How to read the directory dynamically with the name
public class ReadJsonFile {
public static void main(String[] args) {
// TODO Auto-generated method stub
JSONParser jsonParser = new JSONParser();
try {
Object obj = jsonParser.parse(new FileReader("./TestNameUS.json"));
// A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.
JSONObject jsonObject = (JSONObject) obj;
JSONArray query = (JSONArray) jsonObject.get("query");
String query1=null;
for(Object str : query) {
query1=(String)str;
}
System.out.println(query1);
System.out.println(query1.replaceAll("^\\('|\\'\\)$", ""));
} catch (Exception e) {
e.printStackTrace();
}
}
}

I am not getting jsonArray in java?

I am trying to get the json data from properties file in java.
emailServer.properties
{
"Servers":
[
{
"Name":"Server1",
"UserName":"abcde#yahoo.in",
"Password":"something",
"Port":"993",
"FolderName":"Server1"
},
{
"Name":"Server2",
"UserName":"fghijk#gmail.co",
"Password":"something",
"Port":"993",
"FolderName":"Server2"
}
]
}
When i am trying to get servers array it is showing The method getJSONArray(String) is undefined for the type JSONObject. How to solve this?
Here is my java code :-
public void configure()
{
JSONParser parser = new JSONParser();
try
{
String propertyFileName = "emailServer.properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propertyFileName);
JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader(inputStream, "StandardCharsets.UTF_8"));
System.out.println(jsonObject);
JSONArray jadata = jsonObject.getJSONArray("Servers");
System.out.println(jadata);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Instead of using
jsonObject.getJSONArray("Servers"),
you can use
JSONArray jadata =(JSONArray)jsonObject.get("Servers")
which may can solve your problem or if you still getting the issues then you can use google json library like Gson which you can find on maven and use below line:
yourjsonPojo[] data = gson.fromJson(jsonString, yourjsonPojo[].class);

Trying to return a value from Java and read it in JavaScript

I have a method in Java that will be returning a JSON object and I am trying to get it to load in to some JavaScript. Here is my code but it is not working:
Java:
public JSONObject ticketListener(TicketMessage message) {
JSONObject listener = new JSONObject();
try {
listener.put("Ticket Messenge", message.getText());
listener.put("Ticket Number", message.getTicketNumber());
listener.put("Operation", message.getOperation());
listener.put("UserID", message.getUserID());
listener.put("Operation Description", message.getOperationDescription());
} catch (JSONException e) {
e.printStackTrace();
}
}
JavaScript:
$scope.ticketListener = function() {
var val = $entry(#com.cmcflex.flex.gui.programs.projectmanager.gui.messenger.ticketListener::getValue())();
};
Please help.

Parse json array android

Hi i'm trying to parse json array from this url. The json array looks like this.
[
{
"id":1,
"introtext":"\u041b\u0438\u043c\u0443\u0437\u0438\u043d\u0430\u0442\u0430 \u0435 \u043e\u0434 \u0430\u043c\u0435\u0440\u0438\u043a\u0430\u043d\u0441\u043a\u043e \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0441\u0442\u0432\u043e \u0432\u043e \u0431\u0435\u043b\u0430 \u0431\u043e\u0458\u0430 \u0434\u043e\u043b\u0433\u0430 \u043e\u043a\u043e\u043b\u0443 8,5 \u043c\u0435\u0442\u0440\u0438. \u041e\u043f\u0440\u0435\u043c\u0435\u043d\u0430 \u0435 \u0441\u043e \u043a\u043b\u0438\u043c\u0430 \u0440\u0435\u0434, \u0422\u0412, \u0414\u0412\u0414 \u0438 \u0431\u0430\u0440. \u041c\u043e\u0436\u0430\u0442 \u0434\u0430 \u0441\u0435 \u0432\u043e\u0437\u0430\u0442 \u0434\u043e 9 \u043b\u0438\u0446\u0430. \u0421\u0435 \u0438\u0437\u043d\u0430\u0458\u043c\u0443\u0432\u0430 \u0441\u043e \u043d\u0430\u0448 \u0448\u043e\u0444\u0435\u0440.\n{AdmirorGallery}..\/katalog\/prevoz\/limo-servis-jasmina\/linkoln\/{\/AdmirorGallery}\n\u00a0",
"image":"http:\/\/zasvadba.mk\/media\/k2\/items\/cache\/787ae9ec9023a82f5aa7e4c1a64f73cb_S.jpg",
"title":"\u041b\u0438\u043c\u0443\u0437\u0438\u043d\u0430 \u041b\u0438\u043d\u043a\u043e\u043b\u043d",
"catid":"20",
"alias":"\u043b\u0438\u043c\u0443\u0437\u0438\u043d\u0430-\u043b\u0438\u043d\u043a\u043e\u043b\u043d-\u043b\u0438\u043c\u043e-\u0441\u0435\u0440\u0432\u0438\u0441-\u0458\u0430\u0441\u043c\u0438\u043d\u0430"
}
]
I'm doing this in my java class
try {
JSONfunctions j=new JSONfunctions();
JSONObject json = j.getJSONfromURL(url);
Log.i("log_tag", json.toString());
String jsonvalues = json.getString("id");
Log.i("DARE", jsonvalues);
}
catch (Exception ex)
{
Log.e("log_tag", "Error getJSONfromURL "+ex.toString());
}
}
But it doesn't work, can anybody help me parse my json array
you will need to make two changes in your current code according to string u have posted here for parsing as Json :
First : change the return type of getJSONfromURL method to JSONArray and return JSONArray from it instead of JSONObject
For example :
public JSONArray getJSONfromURL(String url){
String str_response="response from server";
// convert response to JSONArray
JSONArray json_Array=new JSONArray(str_response);
return json_Array; //<< retun jsonArray
}
Second : change your code as for getting value from JsonArray :
try {
JSONfunctions j=new JSONfunctions();
JSONArray jArray = j.getJSONfromURL(url);
Log.i("log_tag", jArray.toString());
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String jsonvalues = json_data.getString("id");
// .. get all value here
Log.i("DARE", jsonvalues);
}
}
catch (Exception ex)
{
Log.e("log_tag", "Error getJSONfromURL "+ex.toString());
}
Of course it doesn't work! You should use json.getJSONArray(...) method for parsing arrays in Json :)
You can Easily do it using gson library.
Here is the code sample:
Your Entity Class will like:
public class ResponseEntity {
#SerializedName("id")
public int id;
#SerializedName("introtext")
public String introtext;
#SerializedName("image")
public String image;
#SerializedName("title")
public String title;
#SerializedName("catid")
public String catid;
#SerializedName("alias")
public String alias;
}
Now Convert this json Array using GSON library.
Gson gson=new Gson();
ResponseEntity[] entities = gson.fromJson(yourResponseAsString.toString(),
ResponseEntity[].class);
Now you have the entity array at entities.
Thanks.

Categories

Resources