I am not getting jsonArray in java? - 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);

Related

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();
}
}
}

Value https://test.com at url of type java.lang.String cannot be converted to JSONObject

I'm trying to get the url as string by calling the method getResponseString below, but I keep getting this error.
Any help or suggestion would be appreciated.
ERROR:
JSONException: Value https://test.com at destinationUrl of type java.lang.String cannot be converted to JSONObject
JSON:
"{"destinationUrl":"https://www.test.com"}"
CODE:
try {
JSONObject responseBodyJSON = new JSONObject(responseBody);
if (responseBodyJSON.length() < 1) {
throw new JSONException("response empty");
} else if (responseBodyJSON.length() == 1) {
return responseBodyJSON.getJSONObject(responseBodyJSON.keys().next()).toString();
} else {
return responseBody;
}
} catch (JSONException e) {
throw new JsonParseException(e);
}
you can get the string directly:
try {
JSONObject responseBodyJSON = new JSONObject(responseBody);
return responseBodyJSON.getString("destinationUrl");
} catch (JSONException e) {
throw new JsonParseException(e);
}
I used kotlin for the solution, yan use java conversion here,Use json parser like this,
gradle : implementation 'com.googlecode.json-simple:json-simple:1.1.1'
import org.json.simple.parser.*
var parser = JSONParser()
val jsonTree = parser.parse(responseBody)
after creating json tree object you can cast to the your model.
enter image description here
here you can see the json tree object you can get the fields values separately.

How to code this json in android

hi I am new in this forum I am trying the following in Android studio, I need to create a json object with this format
{
"enviaya_account": "Y0DCRGIU",
"carrier_account": null,
"api_key":"YOUR_API_KEY",
"shipment":{
"shipment_type":"Package",
"parcels":[
{
"quantity":"1",
"weight":"3",
"weight_unit":"kg",
"length":"10",
"height":"20",
"width":"30",
"dimension_unit":"cm"
}
]
},
"origin_direction":{
"country_code":"MX",
"postal_code":"11550"
},
"destination_direction":{
"country_code":"MX",
"postal_code":"01210"
},
"insured_value":"5000",
}
"insured_value_currency":"MXN"
}
but I can not integrate it well since it marks me errors could someone help me please? the code that I have is this:
JSONObject Request = new JSONObject();
JSONObject shipment = new JSONObject();
JSONArray parcels = new JSONArray();
JSONObject parcel= new JSONObject();
JSONObject origin_direction = new JSONObject();
JSONObject destination_direction = new JSONObject();
try {
Request.put("enviaya_account","Y0DCRGIU");
Request.put("carrier_account","");
Request.put("api_key","xxxxxxxxxxxxxxxxxxxxxxxxxxx");
shipment.put("shipment_type","package");
Request.put("shipment",shipment);
parcel.put("quantity","1");
parcel.put("weight","10.98");
parcel.put("weight_unit","kg");
parcel.put("length","39");
parcel.put("height","39");
parcel.put("width","29");
parcel.put("dimension_unit","cm");
parcels.put(parcel);
Request.put("parcels",parcels);
origin_direction.put("country_code","MX");
origin_direction.put("postal_code","29267");
destination_direction.put("country_code","MX");
destination_direction.put("postal_code","34200");
Request.put("origin_direction",origin_direction);
Request.put("destination_direction",destination_direction);
Request.put("insured_value","0");
Request.put("insured_value_currency","MXN");
} catch (JSONException e) {
e.printStackTrace();
}
edt.setText(Request.toString());
but when I try to check it in POSTMAN it tells me that the parcels object does not exist
As far as I know since "parcels" is defined as a JSONArray object, you need to call add method.
parcels.put(parcel);
// should instead be
parcels.add(parcel);
I have changed your code of some part.
JSONObject Request = new JSONObject();
JSONObject shipment = new JSONObject();
JSONArray parcels = new JSONArray();
JSONObject parcel= new JSONObject();
JSONObject origin_direction = new JSONObject();
JSONObject destination_direction = new JSONObject();
try {
Request.put("enviaya_account","Y0DCRGIU");
Request.put("carrier_account","");
Request.put("api_key","xxxxxxxxxxxxxxxxxxxxxxxxxxx");
shipment.put("shipment_type","package");
parcel.put("quantity","1");
parcel.put("weight","10.98");
parcel.put("weight_unit","kg");
parcel.put("length","39");
parcel.put("height","39");
parcel.put("width","29");
parcel.put("dimension_unit","cm");
parcels.put(parcel);
shipment.put("parcels",parcels);
Request.put("shipment",shipment);
origin_direction.put("country_code","MX");
origin_direction.put("postal_code","29267");
destination_direction.put("country_code","MX");
destination_direction.put("postal_code","34200");
Request.put("origin_direction",origin_direction);
Request.put("destination_direction",destination_direction);
Request.put("insured_value","0");
Request.put("insured_value_currency","MXN");
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("Json value", String.valueOf(Request));
this give me result like below screen shot.

Can not convert json string to object

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"}

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