If the array is defined in the file but is empty, like:
...
"kl":[]
...
Then getJSONArray("kl") will return an empty array, but the object is not null. Then, if you do this:
kl = c.getJSONArray("kl");
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
kl is not null and kl.getJSONObject(0) will throw an exception - there is no first element in the array.
Instead you can check the length(), e.g.:
kl = c.getJSONArray("kl");
if(kl != null && kl.length() > 0 ){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
Answer from T.Gounelle on Stack OverflowIf the array is defined in the file but is empty, like:
...
"kl":[]
...
Then getJSONArray("kl") will return an empty array, but the object is not null. Then, if you do this:
kl = c.getJSONArray("kl");
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
kl is not null and kl.getJSONObject(0) will throw an exception - there is no first element in the array.
Instead you can check the length(), e.g.:
kl = c.getJSONArray("kl");
if(kl != null && kl.length() > 0 ){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
You can also use isEmpty() method, this is the method we use to check whether the list is empty or not. This method returns a Boolean value. It returns true if the list is empty otherwise it gives false. For example:
if (!k1.isEmpty()) {
klassenID[i] = kl.getJSONObject(0).getString("id");
}
Your code is wrong. Try this code to test the JSON array:
String jsonString = "[ {"
+ "\"TimeStamp\": \"20:10\","
+ "\"PipeTemp\": \"31.5\","
+ "\"ChocolateMixingTemp\": \"25\","
+ "\"WaterCoolingTemp\": \"5\","
+ "\"WaterMixingTemp\": \"0\","
+ "\"WaterHeatingTemp\": \"0\",},"
+ "{"
+ "\"TimeStamp\": \"20:00\","
+ "\"PipeTemp\": \"35.5\","
+ "\"ChocolateMixingTemp\": \"28\","
+ "\"WaterCoolingTemp\": \"3\","
+ "\"WaterMixingTemp\": \"15\","
+ "\"WaterHeatingTemp\": \"0\","
+ "}]";
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println(jsonArray);
for (int n = 0; n < jsonArray.length(); n++) {
JSONObject jsonObject = jsonArray.getJSONObject(n);
System.out.println((String) jsonObject.get("TimeStamp"));
}
First, your json string is not properly formatted, please see below one formatted:
String s="[ {"
+ "\"TimeStamp\": \"20:10\","
+ "\"PipeTemp\": \"31.5\","
+ "\"ChocolateMixingTemp\": \"25\","
+ "\"WaterCoolingTemp\": \"5\","
+ "\"WaterMixingTemp\": \"0\","
+ "\"WaterHeatingTemp\": \"0\",},"
+ "{"
+ "\"TimeStamp\": \"20:00\","
+ "\"PipeTemp\": \"35.5\","
+ "\"ChocolateMixingTemp\": \"28\","
+ "\"WaterCoolingTemp\": \"3\","
+ "\"WaterMixingTemp\": \"15\","
+ "\"WaterHeatingTemp\": \"0\","
+ "}]";
Second, I don't see your jsonObject getting initialized with anything. If you want to use values from json use jsonArray.get(index) method.
From your JSON data, it seem skills is an array of objects.
"skills": [],
"skills": [
"skill_1": {},
"skill_2": {}
]
But your Java code defines it as Map:
public Map<String, Skill> skills;
That's why you got an exception when trying to convert the array to a map directly. If you can't change the POJO's Profile, you should have an intermediate step to convert the list to a Map.
public class SkillsMapDeserializer extends JsonDeserializer<Map<String, Skill>> {
@Override
public Map<String, Skill> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final List<Map<String,Skill>> skills = jsonParser.readValueAs(new TypeReference<List<Map<String,Skill>>>>() {
});
return functionConvertListToMapWithParam(skills);
}
}
skills is not a map. it should be list of objects. try to modify your POJO like below:-
public class Profile {
@JsonProperty("name")
private String name;
@JsonProperty("age")
private Integer age;
@JsonProperty("skills")
private List < Object > skills = null;
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
@JsonProperty("age")
public Integer getAge() {
return age;
}
@JsonProperty("age")
public void setAge(Integer age) {
this.age = age;
}
@JsonProperty("skills")
public List < Object > getSkills() {
return skills;
}
@JsonProperty("skills")
public void setSkills(List < Object > skills) {
this.skills = skills;
}
}
You can use method from is* family:
Gson gson = new GsonBuilder().create();
String[] jsons = {"[]", "[ ]", "[\r\n]", "{}", "{\"error\":\"Internal error\"}"};
for (String json : jsons) {
JsonElement root = gson.fromJson(json, JsonElement.class);
if (root.isJsonObject()) {
JsonElement error = root.getAsJsonObject().get("error");
System.out.println(error);
}
}
prints:
null
"Internal error"
There is no point to check "[]" string because between brackets could be many different white characters. JsonElement is a root type for all JSON objects and is safe to use.
Try this
if(!errorMessage[0]==null)
If your array is empty at position 0, it is returned null, or if you declare the array size when you declare it to be done:
if(!errorMessage[0]=="")
Something like this should work:
DBObject one = cur.next();
if (one.get("photos") == null)
one.put("photos", new Object[0]);
return JSON.serialize(one);
I needed to do similar and found a minor alternative to the accepted answer is to use JSONArray:
one.put("photos", new JSONArray());
assuming:
String jsonString = "pac_selected": [{
"pack_selected_id": "7"
}, {}, {
"pack_selected_id": 45
}]
I would do the following, based on this answer:
JSONArray list = new JSONArray();
JSONArray jsonArray = new JSONArray(jsonstring);
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
String element = jsonArray.get(i);
if (!element.isEmpty())
{
list.put(element);
}
}
}
Then just use list instead of jsonArray.
Try this method
String json = .... // your json
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> data = new Gson().fromJson(json, type);
for (Iterator<Map.Entry<String, Object>> it = data.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
if (entry.getValue() == null) {
it.remove();
} else if (entry.getValue().getClass().equals(ArrayList.class)) {
if (((ArrayList<?>) entry.getValue()).size() == 0) {
it.remove();
}
}
}
String json1 = new GsonBuilder().setPrettyPrinting().create().toJson(data);
System.out.println("Latest json "+json1);
Add this to pom.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>