This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I've got this JSON in JSON object like this
JSONObject obj = new JSONObject(json);
I now want to get back "TRUE" (control F to find where that is)
{"version":"1.0","encoding":"UTF-8","feed":{"xmlns":"Lorum","xmlns$openSearch":"Ipsum","xmlns$gsx":"Dolor","id":{"$t":"Lorum"},"updated":{"$t":"2016-07-30T07:40:03.369Z"},"category":[{"scheme":"Ipsum","term":"Dolar"}],"title":{"type":"text","$t":"Sheet1"},"link":[{"rel":"alternate","type":"application/atom+xml","href":"Lorum"},{"rel":"Ipsum","type":"application/atom+xml","href":"Dolor"},{"rel":"Lorum","type":"application/atom+xml","href":"Ipsum"},{"rel":"self","type":"application/atom+xml","href":"Dolor"}],"author":[{"name":{"$t":"spark"},"email":{"$t":"Lorum"}}],"openSearch$totalResults":{"$t":"1"},"openSearch$startIndex":{"$t":"1"},"entry":[{"id":{"$t":"Ipsum"},"updated":{"$t":"2016-07-30T07:40:03.369Z"},"category":[{"scheme":"Dolor","term":"Lorum"}],"title":{"type":"text","$t":"Ipsum"},"content":{"type":"text","$t":"parko2: TRUE"},"link":[{"rel":"self","type":"application/atom+xml","href":"Lorum"}],"gsx$parko1":{"$t":"TRUE"},"gsx$parko2":{"$t":"FALSE"},"gsx$indexfilteraanotisblankaarowsfilteraanotisblankaa":{"$t":""}}]}}
JSONObject obj = new JSONObject(json);
JSONObject obj1 =obj.getJsonObject("feed");
JsonArray array = obj1.getJsonArray("entry");
You will get array of entry array
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I'm trying to read parameters for a function from a JSON file, but I always got a empty string.
This is my JSON file
{
"prova":"https://urltest",
"reale":"https://url"
}
and my code is
String key_param = "folder/param.json";
File param = new File ("/tmp/" + key_param);
/*
...
CODE FOR CHECKING FILE EXISTENCE
...
*/
JSONParser new_pars = new JSONParser();
Reader myreader = new FileReader(param);
JSONObject json_param = (JSONObject) new_pars.parse(myreader);
String url = new String();
if (ambiente == "prova") //<-- this has been previously set in the code
url = (String) json_param.get("prova");
else if (ambiente == "reale")
url = (String) json_param.get("reale");
System.out.println("url = " + url);
I always get url = from the execution.
What's wrong?
EDIT
It's not the json handling which is faulty, but my attempt to compare strings in Java using ==
Are there any errors when you use jsonobject.get(value) ?
Same as #Dave Newton's answer. You can not compare to string with operation ==. You should use equals or equalsIgnorecase to compare
This question already has answers here:
Convert Json Array to normal Java list
(16 answers)
Closed 3 years ago.
I am using openjdk 11 and I am calling an api that is returning content type json. I parsing the response and converting into a string like this ( Need to do it this way as I am expecting responses in different formats/structure):
HttpEntity entity = response.getEntity();
try
{
responseBody = EntityUtils.toString( entity );
}
catch ( Exception e )
{
LOG.error( "Unable to parse response", e );
e.printStackTrace();
}
Where response is a org.apache.http.HttpResponse type object.
After converting into a string, the response looks like :
["abc","bcd","cde"]
Now, I was trying to put this into jsonObject or JsonArray as
JSONArray jsonArray = new JSONArray(responseBody);
Arrays.asList(jsonArray).stream().forEach(e-> LOG.info("Connector: " + e));
While my jsonArray looks good, getting error like :
["abc","bcd","cde"] is not an array
Question is : How to convert that jsonArray into a List in Java ?
I assume JSONArray comes from Android. You can just do this:
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
Source: Convert Json Array to normal Java list
This question already has answers here:
Is it ok to save a JSON array in SharedPreferences?
(9 answers)
Closed 6 years ago.
I am new in Android. I want to save JSON Array in Shared Preferences.
Here is My Java Code:
while (managedCursor.moveToNext())
{
JSONObject jsonObject = new JSONObject();
try
{
jsonObject.put("number", number);
jsonObject.put("type", type);
jsonObject.put("fDate", fDate);
jsonObject.put("duration", duration);
}
catch (Exception e)
{
e.printStackTrace();
}
jsonArray.put(jsonObject);
}
managedCursor.close();
Log.d("array", jsonArray.toString());
Firstly, I'd use Gson for converting json to/from Java objects,then can use something like following to store in SharedPreferences.
public void storeMyData(MyPojo myPojo) {
preferences.edit().putString(SOME_SHARED_PREF_KEY, gson.toJson(myPojo)).commit();
}
convert json to string and save to sharedpreference
preferences.edit().putString(SOME_SHARED_PREF_KEY,jsonobject.toString()).commit();
on reading from sharedPreference convert back to json by
String string = preferences.getString(SOME_SHARED_PREF_KEY, null);
JsonObject jsonObject = new JsonObject(string);
This question already has answers here:
Convert a JSON string to object in Java ME?
(14 answers)
Closed 8 years ago.
i need to convert this String JSON to a Java Object:
{"estabelecimento":[{"id":"5","idUsuario":"5","razaoSocial":"Bibi LTDA","nomeFantasia":"BibiPizza","telefone":"22121212","email":"ronaldo#bibi.com","gostaram":"0"},{"id":"8","idUsuario":"1","razaoSocial":"Nestor Latuf LTDA","nomeFantasia":"Nestor Sorvetes","telefone":"32343233","email":"nestor#Sorvete.com","foto":"","gostaram":"0"},{"id":"9","idUsuario":"1","razaoSocial":"Comercio Alimenticio Rivaldo","nomeFantasia":"Rogers Burguer","telefone":"210021020","email":"roger#gmail.com","foto":"","gostaram":"0"}]}
I try this, but not work:
//JSONArray jArr = new JSONArray(br.toString());
//JSONObject jObj = new JSONObject(br.toString());
//JSONArray jArr = jObj.getJSONArray("list");
JSONArray jArr = new JSONArray(br.toString());
for (int i=0; i < jArr.length(); i++) {
JSONObject obj = jArr.getJSONObject(i);
estabelecimento.setId(obj.getLong("id"));
estabelecimento.setIdUsuario(obj.getLong("idUsuario"));
estabelecimento.setRazaoSocial(obj.getString("razaoSocial"));
estabelecimento.setNomeFantasia(obj.getString("nomeFantasia"));
estabelecimento.setTelefone(obj.getString("telefone"));
estabelecimento.setEmail(obj.getString("email"));
estabelecimento.setGostaram(obj.getInt("gostaram"));
estabelecimentoList.add(estabelecimento);
}
con.disconnect();
How can i obtain a Java Object? Someone can help? tks.
You can use the Gson lib of google:
public class MyClass {
private int data1 = 100;
private String data2 = "hello";
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
//getter and setter methods needed
}
String str = {"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]};
com.google.gson.Gson gson = new com.google.gson.Gson();
//To convert json string to class use fromJson
MyClass obj = gson.fromJson(str, MyClass .class);
//To convert class object to json string use toJson
String json = gson.toJson(obj);
At high level two major steps:
Generate a Java class from your JSON, e.g. by using this generator or similar: http://www.jsonschema2pojo.org/
Use Jackson processor to deserialize your JSON file:
ObjectMapper mapper = new ObjectMapper();
YourGeneratedClass obj = (YourGeneratedClass) mapper.readValue(new File("path-to-your-json-file"), YourGeneratedClass.class);
More about Jackson: http://jackson.codehaus.org/
You can also create YourGeneratedClass manually if you feel comfortable enough with this.
I am currently writing some code in a servlet that gets data from the database and returns it to the client. What I am having problems with is inserting the array of dates I have collected and adding them to my JSON object that I will return to the client.
Here is the code I'm trying but it keeps giving errors
dates = ClassdatesDAO.getdate(dates);
ArrayList<String> ClassDates = new ArrayList<String>();
ClassDates = dates.getClassdates();
response.setContentType("application/json");
JSONObject Dates = new JSONObject();
Dates.put("dates", new JSONArray(ClassDates));
In my IDE I get this error over the ClassDates in the JSONArray
The constructor JSONArray(ArrayList) is undefined
You are passing ArrayList instance instead of an Array. So, convert the list into an array and then pass it as an argument like this
Dates.put("dates", new JSONArray(ClassDates.toArray(new String[ClassDates.size()])));
Note : json API has a method signature accepting java.util.Collection. So, you are using some other library or older version
JSONObject Dates = new JSONObject();
JSONArray datesJSONArray = new JSONArray();
for (String date : ClassDates)
datesJSONArray.put(date);
try {
Dates.put("dates", datesJSONArray);
} catch (JSONException e) {
e.printStackTrace();
}