Json empty object java

Getting empty object in REST service in Java

And following the jQuery method I call when input fields in the form are filled and create button is clicked.

function createEntry() < var formData = JSON.stringify(< "ID" : $("input[name='txtID']").val(), "tableID" : $("input[name='txtTableID']").val(), "custNick" : $("input[name='txtNick']").val() >); console.log(formData); //Just to see if form details are JSON encoded. $.ajax(< type: "POST", contentType: "application/json", url: baseURL, dataType: "json", data: formData, success: function(data) < console.log("Customer Added!"); $("div.response").append("

New Customer ("+ $("input[name='txtNick']").val() +") Added on the Server

"); > >); >

But on server, I’m getting empty «customer» object, what am I doing wrong here? Please let me know if you need any further details (regarding Customer class model). Update: Following is Customer class.

/*ignore imports, all required imports are included */ @XmlRootElement public class Customer < private int id; private int tableid; private String custnick; public int getID() < return id; >public void setID(int id) < this.id = id; >. . /* Similar Setter-Getter Methods for the fields */ > 

I guess the problem has something to do with XML schema of my «Customer» class and the node names I send in JSON object is not matching with schema that’s why it may not be able to map fields with setter methods of my model class, not sure though.

Читайте также:  Java static class compile

Источник

Empty object in browser when returning JSONObject

When accessing to the URL of the method in the browser, I get < >, it means that the object is empty. So, I tried to use :

return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).cacheControl(cacheControl).build(); 

So, I get in the browser <"userExists" : false>But I didn’t understand why when returning simply the JSONObject, we get in the browser an empty object.

because java objects are not stored as string so returning object and its string representation is entirely different thing.

Your browser doesn’t know how your complex object is serialized — Java, .Net, Python.. So is your HTTP protocols. But they do understand string objects.

But in the code I have an example that returns a simple java object (all the attributes are String) and in this example, the object isn’t empty in the browser. So, why is it empty in the case of JSONObject ?

1 Answer 1

Most JAX-RS implementations come with a provider for mapping response entities to JSON. So when you write:

return Response.ok(jsonObject, MediaType.APPLICATION_JSON).build(); 

You are basically requesting that the JAX-RS provider marshall the JSONObject into JSON for you. The only problem being that JSONObject isn’t really meant to be serialized this way. Instead its meant to be used to build a JSON representation incrementally, then convert that representation into a JSON string value. You have two options:

  1. Create a POJO containing all the fields you want to send back to the client. Return this POJO in your method and it will be automatically converted to JSON (`return Response.ok(myPojo, MediaType.APPLICATION_JSON).build()
  2. Return the JSON data directly as a String (which you already did in your example that works).

Источник

How to Test If Json Collection Object Is Empty in Java

How to test if JSON Collection object is empty in Java

How to check if JSON object is empty in Java?

Neither of those two things are null ; they are arrays. The result is exactly what you would expect.

One of your arrays is empty, the other contains a single element that is null .

If you want to know if an array is empty, you would need to get the array, then check its length.

JSONObject myJsonObject = 
new JSONObject("");

if (myJsonObject.getJSONArray("null_object_1").length() == 0) .
>

Edit to clarify: An array having no elements (empty) and an array that has an element that is null are completely different things. In the case of your second array it is neither null nor empty. As I mentioned it is an array that has a single element which is null . If you are interesting in determining if that is the case, you would need to get the array then iterate through it testing each element to see if it were null and acting upon the results accordingly.

Check if Json Array is empty or contains one Json Object

You can check the data array length like this:

Checking if a JSON key is empty before adding to constructor

org.json.JSONException: No value for description

You should check Json has. boolean has (String name)

Returns true if this object has a mapping for name.
NULL

if (items.has("description")) 
String description= items.getString("description"));
>

how to check if a JSONArray is empty in java?

If the array is defined in the file but is empty, like:

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");
>

How to check empty array string before creating json object in java?

You can use method from is* family:

Gson gson = new GsonBuilder().create();

String[] jsons = <"[]", "[ ]", "[\r\n]", "<>", "">;
for (String json : jsons) JsonElement root = gson.fromJson(json, JsonElement.class);
if (root.isJsonObject()) JsonElement error = root.getAsJsonObject().get("error");
System.out.println(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.

Источник

Representing null in JSON

What is the preferred method for returning null values in JSON? Is there a different preference for primitives? For example, if my object on the server has an Integer called «myCount» with no value, the most correct JSON for that value would be:

I like the convention for collections to be represented in the JSON as an empty collection http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html An empty Array would be represented:

  • Objects are preferred over primitives.
  • Empty collections are preferred over null.
  • Objects with no value are represented as null.
  • Primitives return their value.

If you are returning a JSON object with mostly null values, you may have a candidate for refactoring into multiple services.

The above JSON was generated from the following Java class.

package jackson; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonApp < public static class Data < public Integer value1; public Integer value2; public String text1; public String text2 = "hello"; public int intValue; public ListmyList = new ArrayList(); public List myEmptyList; public Boolean boolean1; public boolean littleboolean; > public static void main(String[] args) throws Exception < ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(new Data())); >> 
 com.fasterxml.jackson.core jackson-core 2.3.0  

There is no best way. Pick what’s easiest to consume for the client in your concrete use case. In the spirit of returning empty collections instead of null , consider if your client is better of with the empty string or null — a string containing the word «null» is indistinguishable from a valid value, don’t do that.

0 or an empty string could very well have different meaning from null, which could have different meaning from the attribute not existing. If you want to represent null, use null. It’s the most explicit.

In Objective-C there is a defined NSNull class which has a singleton instance. A reference to that instance is equivalent to JSON’s null . I would guess that another language could do the same thing. Of course, one would have to check the class of the received object before casting to the presumed class — be «null aware», as it were.

Note that having a «null» list isn’t best practice in Java either: if the list is expected to be empty, initialise it to an empty list. If it is required to remain empty (e.g. because it will be replaced wholesale by a new list rather than modified to add values), initialise it to the empty list (i.e. Collections.emptyList() ). Doing so avoids null reference bugs that can be a pain otherwise.

@HotLicks — that’s only possible because Objective-C is dynamically typed. In Java, for instance, you couldn’t have a (useful) Null class because you would only be able to assign its values to objects of its own type or of type Object .

8 Answers 8

Let’s evaluate the parsing of each:

var json1 = '<>'; var json2 = ''; var json3 = ''; var json4 = ''; var json5 = ''; var json6 = ''; console.log(JSON.parse(json1)); // <> console.log(JSON.parse(json2)); // console.log(JSON.parse(json3)); // console.log(JSON.parse(json4)); // console.log(JSON.parse(json5)); // console.log(JSON.parse(json6)); //

The tl;dr here:

The fragment in the json2 variable is the way the JSON spec indicates null should be represented. But as always, it depends on what you’re doing — sometimes the «right» way to do it doesn’t always work for your situation. Use your judgement and make an informed decision.

This returns an empty object. There is no data there, and it’s only going to tell you that whatever key you’re looking for (be it myCount or something else) is of type undefined .

In this case, myCount is actually defined, albeit its value is null . This is not the same as both «not undefined and not null «, and if you were testing for one condition or the other, this might succeed whereas JSON1 would fail.

This is the definitive way to represent null per the JSON spec.

In this case, myCount is 0. That’s not the same as null , and it’s not the same as false . If your conditional statement evaluates myCount > 0 , then this might be worthwhile to have. Moreover, if you’re running calculations based on the value here, 0 could be useful. If you’re trying to test for null however, this is actually not going to work at all.

In this case, you’re getting an empty string. Again, as with JSON2, it’s defined, but it’s empty. You could test for if (obj.myString == «») but you could not test for null or undefined .

This is probably going to get you in trouble, because you’re setting the string value to null; in this case, obj.myString == «null» however it is not == null .

This will tell you that your array myArray exists, but it’s empty. This is useful if you’re trying to perform a count or evaluation on myArray . For instance, say you wanted to evaluate the number of photos a user posted — you could do myArray.length and it would return 0 : defined, but no photos posted.

Источник

Returning Empty JSON Object in Spring Framework

Sometimes you may want to return an empty JSON object from a Spring Framework controller action, be it in a REST API or just a regular controller action. This could for example be the case if you are issuing an AJAX request from jQuery; if you specify the data type to be JSON, the success handler will not be invoked if there is no response body, because the response body does not contain valid JSON. Therefore it may be desirable to simply return <> .

Assuming that you have the Jackson JSON library on your classpath, this can be achieved with the following code.

The concept is to simply annotate a class with Jackson’s @JsonSerialize annotation. Since we do not want any fields/properties in the response, we will just leave the class empty.

@JsonSerialize public class EmptyJsonResponse

Now we can use this class together with Spring Framework’s ResponseEntity class.

@RestController public class CompanyController < @RequestMapping(value = "/api/something", method = RequestMethod.GET) public ResponseEntity something() < return new ResponseEntity(new EmptyJsonResponse(), HttpStatus.OK); >>

Alternatively, one could use the @ResponseBody annotation above the method instead of annotating one’s controller with @RestController . The latter annotation is simply a convenient way of doing this for all controller actions.

That’s all there is to do. The above endpoint will return 200 OK and <> as the response body.

Источник

Оцените статью