5

I want to make a JSON object and define its keys. I will initialize values to it later. Is there any way to do that? I want something like this when i print the JSONObject before initializing values to it and after defining it:

education:{ "name":"", "year":, "qualification": }

i.e only keys are there,no values to them exist. how do i define this "education" object. i know its defination can be:

JSONObject education=new JSONObject();

but where do the keys fit in here?

3
  • 3
    No simply you cannot, and prepare your json with empty values instead of no value. Then you can fill it later. Commented Nov 25, 2017 at 6:44
  • Did you even try searching google? I found this example fairly quickly. Please review How to Ask. Commented Nov 25, 2017 at 6:49
  • Do null values solve your problem? education:{ "name":null, "year":null, "qualification": null } Commented Nov 25, 2017 at 7:21

2 Answers 2

2

You can simply create a JSON object and then put each attribute with an empty string.

here is the code:

JSONObject education = new JSONObject();
education.put("name",new String());
education.put("year",new String()); 
education.put("qualification",new String());
Sign up to request clarification or add additional context in comments.

Comments

1

You simply cannot have only keys defined. What you are essentially trying to say is I want these fields, but without defining the type of these fields. So even if let's say hypothetically it was allowed, how would you know what to expect as a value for any of the field.

education:{ "name":"", "year":, "qualification": }

From just this declaration, we cannot figure out is name again a JSON object? or a String field? same goes with other fields.

So the solution to your query would be, have default values for these fields. Ex. if it's a string have ""(empty string), if it's an object put null.

Then in turn you can modify them as and when you get actual values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.