Sort
Profile photo for Kjetil Valstadsve

Sorry, you can't do this. Look at the JSON spec:

http://www.json.org/

It's very simple. The first words of the first bullet point say it clearly: "A collection of name/value pairs".

Keep in mind that JSON is basically lifted from Javascript syntax for object and array literals. Your map in Java is mapped to/from a Javascript object, when and if it is evaluated in a browser context. A Javascript object has fields, and the fields have names. Names can't be objects, they are strings.

Jackson is doing what it can here, resorting to toString().

You can, of course, create an object where the fields ha

Sorry, you can't do this. Look at the JSON spec:

http://www.json.org/

It's very simple. The first words of the first bullet point say it clearly: "A collection of name/value pairs".

Keep in mind that JSON is basically lifted from Javascript syntax for object and array literals. Your map in Java is mapped to/from a Javascript object, when and if it is evaluated in a browser context. A Javascript object has fields, and the fields have names. Names can't be objects, they are strings.

Jackson is doing what it can here, resorting to toString().

You can, of course, create an object where the fields have names that are JSON strings. And, of course, this would be insane.

On second thought, you probably can't even do that, since field names obviously can't hold arbitrary characters. So this would require some string encoding of JSON that obeys Javascript syntax for field names! Is there a quora board for mad computer science?

Profile photo for Toby Thain

As Kjetil Valstadsve's answer says, in JSON, keys must be strings. However, you can still represent your map in JSON, just not as a JSON object:

[code=javascript]
[
[ {"LongAttr":123, "IntegerAtt":456}, "stringValue" ],
[ {"LongAttr":129, "IntegerAtt":442}, "somethingelse" ],
...
]
[/code]

You can even probably persuade Jackson to do this.

Where do I start?

I’m a huge financial nerd, and have spent an embarrassing amount of time talking to people about their money habits.

Here are the biggest mistakes people are making and how to fix them:

Not having a separate high interest savings account

Having a separate account allows you to see the results of all your hard work and keep your money separate so you're less tempted to spend it.

Plus with rates above 5.00%, the interest you can earn compared to most banks really adds up.

Here is a list of the top savings accounts available today. Deposit $5 before moving on because this is one of th

Where do I start?

I’m a huge financial nerd, and have spent an embarrassing amount of time talking to people about their money habits.

Here are the biggest mistakes people are making and how to fix them:

Not having a separate high interest savings account

Having a separate account allows you to see the results of all your hard work and keep your money separate so you're less tempted to spend it.

Plus with rates above 5.00%, the interest you can earn compared to most banks really adds up.

Here is a list of the top savings accounts available today. Deposit $5 before moving on because this is one of the biggest mistakes and easiest ones to fix.

Overpaying on car insurance

You’ve heard it a million times before, but the average American family still overspends by $417/year on car insurance.

If you’ve been with the same insurer for years, chances are you are one of them.

Pull up Coverage.com, a free site that will compare prices for you, answer the questions on the page, and it will show you how much you could be saving.

That’s it. You’ll likely be saving a bunch of money. Here’s a link to give it a try.

Consistently being in debt

If you’ve got $10K+ in debt (credit cards…medical bills…anything really) you could use a debt relief program and potentially reduce by over 20%.

Here’s how to see if you qualify:

Head over to this Debt Relief comparison website here, then simply answer the questions to see if you qualify.

It’s as simple as that. You’ll likely end up paying less than you owed before and you could be debt free in as little as 2 years.

Missing out on free money to invest

It’s no secret that millionaires love investing, but for the rest of us, it can seem out of reach.

Times have changed. There are a number of investing platforms that will give you a bonus to open an account and get started. All you have to do is open the account and invest at least $25, and you could get up to $1000 in bonus.

Pretty sweet deal right? Here is a link to some of the best options.

Having bad credit

A low credit score can come back to bite you in so many ways in the future.

From that next rental application to getting approved for any type of loan or credit card, if you have a bad history with credit, the good news is you can fix it.

Head over to BankRate.com and answer a few questions to see if you qualify. It only takes a few minutes and could save you from a major upset down the line.

How to get started

Hope this helps! Here are the links to get started:

Have a separate savings account
Stop overpaying for car insurance
Finally get out of debt
Start investing with a free bonus
Fix your credit

Profile photo for Paulina Jonušaitė

HashMap has no way of identifying the key class as “custom” or not.

Any broken behaviour you notice in a HashMap usually points to:

  • fucked up hashCode method, or even worse, the fact that you didn’t even bother to override it
  • fucked up equals method, or even worse, the fact that you didn’t even bother to override it
  • mutual fuck up, where you somehow ended up in a situation where foo.equals(bar), yet foo.hashCode() != bar.hashCode()

Specifically, if you use the default implementation of hashCode and equals, they assume that two things are only equal if they are the same exact thing, and therefore yo

HashMap has no way of identifying the key class as “custom” or not.

Any broken behaviour you notice in a HashMap usually points to:

  • fucked up hashCode method, or even worse, the fact that you didn’t even bother to override it
  • fucked up equals method, or even worse, the fact that you didn’t even bother to override it
  • mutual fuck up, where you somehow ended up in a situation where foo.equals(bar), yet foo.hashCode() != bar.hashCode()

Specifically, if you use the default implementation of hashCode and equals, they assume that two things are only equal if they are the same exact thing, and therefore you will never be able to retrieve contents from your hash map when you lose the reference to your original key.

  1. class Foo { 
  2. private String id; 
  3. public Foo(String id) { 
  4. this.id = id; 
  5. } 
  6. } 
  7.  
  8. // ... 
  9.  
  10. Map<Foo, Integer> fooMap = new HashMap<>(); 
  11. fooMap.put(new Foo("foo"), 420); 
  12.  
  13. // prints "null" 
  14. // even if the contents are the same, these objects are different 
  15. System.out.println(fooMap.get(new Foo("foo")));  
Profile photo for Assistant
Assistant

To serialize a java.util.Map with a custom class as the key using the Jackson JSON processor, you'll need to follow a few steps. Jackson requires that the key class implements the hashCode() and equals() methods properly, so it can manage the keys in the map. Additionally, you may need to register a custom serializer for your key class if it requires special handling.

Here’s a step-by-step guide:

1. Implement hashCode() and equals()

Ensure that your custom key class overrides the hashCode() and equals() methods. This is crucial for the correct functioning of the map.

  1. public class CustomKey { 
  2. pr 

To serialize a java.util.Map with a custom class as the key using the Jackson JSON processor, you'll need to follow a few steps. Jackson requires that the key class implements the hashCode() and equals() methods properly, so it can manage the keys in the map. Additionally, you may need to register a custom serializer for your key class if it requires special handling.

Here’s a step-by-step guide:

1. Implement hashCode() and equals()

Ensure that your custom key class overrides the hashCode() and equals() methods. This is crucial for the correct functioning of the map.

  1. public class CustomKey { 
  2. private String id; 
  3.  
  4. public CustomKey(String id) { 
  5. this.id = id; 
  6. } 
  7.  
  8. // Getters, setters, etc. 
  9.  
  10. @Override 
  11. public boolean equals(Object o) { 
  12. if (this == o) return true; 
  13. if (!(o instanceof CustomKey)) return false; 
  14. CustomKey that = (CustomKey) o; 
  15. return id.equals(that.id); 
  16. } 
  17.  
  18. @Override 
  19. public int hashCode() { 
  20. return id.hashCode(); 
  21. } 
  22. } 

2. Create the Map

Create your map with the custom key and a value type (e.g., String):

  1. Map<CustomKey, String> map = new HashMap<>(); 
  2. map.put(new CustomKey("key1"), "value1"); 
  3. map.put(new CustomKey("key2"), "value2"); 

3. Serialize the Map

Use Jackson to serialize the map. You may need to configure an ObjectMapper.

  1. import com.fasterxml.jackson.databind.ObjectMapper; 
  2.  
  3. public class Main { 
  4. public static void main(String[] args) { 
  5. try { 
  6. ObjectMapper objectMapper = new ObjectMapper(); 
  7.  
  8. Map<CustomKey, String> map = new HashMap<>(); 
  9. map.put(new CustomKey("key1"), "value1"); 
  10. map.put(new CustomKey("key2"), "value2"); 
  11.  
  12. // Serialize the map 
  13. String jsonString = objectMapper.writeValueAsString(map); 
  14. System.out.println(jsonString); 
  15. } catch (Exception e) { 
  16. e.printStackTrace(); 
  17. } 
  18. } 
  19. } 

4. Custom Serializer (if needed)

If your custom key class needs special handling during serialization, you can create a custom serializer.

  1. import com.fasterxml.jackson.core.JsonGenerator; 
  2. import com.fasterxml.jackson.databind.SerializerProvider; 
  3. import com.fasterxml.jackson.databind.annotation.JsonSerialize; 
  4. import com.fasterxml.jackson.databind.JsonSerializer; 
  5.  
  6. @JsonSerialize(using = CustomKeySerializer.class) 
  7. public class CustomKey { 
  8. // ... existing code ... 
  9. } 
  10.  
  11. class CustomKeySerializer extends JsonSerializer<CustomKey> { 
  12. @Override 
  13. public void serialize(CustomKey value, JsonGenerator gen, SerializerProvider serializers) throws IOException { 
  14. gen.writeString(value.getId()); // or however you want to serialize it 
  15. } 
  16. } 

Conclusion

By following these steps, you can serialize a java.util.Map with a custom class as the key using Jackson. Ensure that your custom key class is properly defined, and if necessary, implement a custom serializer to control how the keys are represented in JSON.

Profile photo for Tirthankar Kundu

Here’s a quick implementation for a small JSON.

The input JSON is:

  1. { 
  2. "name": "John Doe", 
  3. "occupation": "Software Engineer", 
  4. "age": 25 
  5. } 

We will first create a bean class for this as below:

  1. import com.google.gson.annotations.Expose; 
  2. import com.google.gson.annotations.SerializedName; 
  3.  
  4. public class Person { 
  5. @SerializedName("name") 
  6. @Expose private String name; 
  7. @SerializedName("occupation") 
  8. @Expose private String occupation; 
  9. @SerializedName("age") 
  10. @Expose private Integer age; 
  11.  
  12. public String getName() { 
  13. return name; 
  14. } 
  15.  
  16. public void setName(String name) { 
  17. this.n 

Here’s a quick implementation for a small JSON.

The input JSON is:

  1. { 
  2. "name": "John Doe", 
  3. "occupation": "Software Engineer", 
  4. "age": 25 
  5. } 

We will first create a bean class for this as below:

  1. import com.google.gson.annotations.Expose; 
  2. import com.google.gson.annotations.SerializedName; 
  3.  
  4. public class Person { 
  5. @SerializedName("name") 
  6. @Expose private String name; 
  7. @SerializedName("occupation") 
  8. @Expose private String occupation; 
  9. @SerializedName("age") 
  10. @Expose private Integer age; 
  11.  
  12. public String getName() { 
  13. return name; 
  14. } 
  15.  
  16. public void setName(String name) { 
  17. this.name = name; 
  18. } 
  19.  
  20. public String getOccupation() { 
  21. return occupation; 
  22. } 
  23.  
  24. public void setOccupation(String occupation) { 
  25. this.occupation = occupation; 
  26. } 
  27.  
  28. public Integer getAge() { 
  29. return age; 
  30. } 
  31.  
  32. public void setAge(Integer age) { 
  33. this.age = age; 
  34. } 
  35.  
  36. @Override public String toString() { 
  37. return "Person{" + 
  38. "name='" + name + '\'' + 
  39. ", occupation='" + occupation + '\'' + 
  40. ", age=" + age + 
  41. '}'; 
  42. } 
  43. } 

It is good to override toString to display the content easily.

Next we implement this bean using Gson as below:

  1. String jsonString = "{'name':'John Doe','occupation': 'Software Engineer', 'age':23}"; 
  2. Gson gson = new Gson(); 
  3. Person person = gson.fromJson(jsonString, Person.class); 
  4. System.out.println(person.toString()); 

Things will be bit tricky when we input JSON array instead of JSON Object.

We use TypeToken in this case as below:

  1. String jsonString = "[{'name':'John Doe','occupation': 'Software Engineer', 'age':23}," + 
  2. "{'name':'Mark Doe','occupation': 'Senior Manager', 'age':40}]"; 
  3. Type type = new TypeToken<List<Person>>() { }.getType(); 
  4. List<Person> persons = gson.fromJson(jsonString, type); 
  5. System.out.println(persons.toString()); 

Check the output of the above codes:

Hope you liked it. Cheers.

Profile photo for Quora User

Here’s the thing: I wish I had known these money secrets sooner. They’ve helped so many people save hundreds, secure their family’s future, and grow their bank accounts—myself included.

And honestly? Putting them to use was way easier than I expected. I bet you can knock out at least three or four of these right now—yes, even from your phone.

Don’t wait like I did. Go ahead and start using these money secrets today!

1. Cancel Your Car Insurance

You might not even realize it, but your car insurance company is probably overcharging you. In fact, they’re kind of counting on you not noticing. Luckily,

Here’s the thing: I wish I had known these money secrets sooner. They’ve helped so many people save hundreds, secure their family’s future, and grow their bank accounts—myself included.

And honestly? Putting them to use was way easier than I expected. I bet you can knock out at least three or four of these right now—yes, even from your phone.

Don’t wait like I did. Go ahead and start using these money secrets today!

1. Cancel Your Car Insurance

You might not even realize it, but your car insurance company is probably overcharging you. In fact, they’re kind of counting on you not noticing. Luckily, this problem is easy to fix.

Don’t waste your time browsing insurance sites for a better deal. A company called Insurify shows you all your options at once — people who do this save up to $996 per year.

If you tell them a bit about yourself and your vehicle, they’ll send you personalized quotes so you can compare them and find the best one for you.

Tired of overpaying for car insurance? It takes just five minutes to compare your options with Insurify and see how much you could save on car insurance.

2. Ask This Company to Get a Big Chunk of Your Debt Forgiven

A company called National Debt Relief could convince your lenders to simply get rid of a big chunk of what you owe. No bankruptcy, no loans — you don’t even need to have good credit.

If you owe at least $10,000 in unsecured debt (credit card debt, personal loans, medical bills, etc.), National Debt Relief’s experts will build you a monthly payment plan. As your payments add up, they negotiate with your creditors to reduce the amount you owe. You then pay off the rest in a lump sum.

On average, you could become debt-free within 24 to 48 months. It takes less than a minute to sign up and see how much debt you could get rid of.

3. You Can Become a Real Estate Investor for as Little as $10

Take a look at some of the world’s wealthiest people. What do they have in common? Many invest in large private real estate deals. And here’s the thing: There’s no reason you can’t, too — for as little as $10.

An investment called the Fundrise Flagship Fund lets you get started in the world of real estate by giving you access to a low-cost, diversified portfolio of private real estate. The best part? You don’t have to be the landlord. The Flagship Fund does all the heavy lifting.

With an initial investment as low as $10, your money will be invested in the Fund, which already owns more than $1 billion worth of real estate around the country, from apartment complexes to the thriving housing rental market to larger last-mile e-commerce logistics centers.

Want to invest more? Many investors choose to invest $1,000 or more. This is a Fund that can fit any type of investor’s needs. Once invested, you can track your performance from your phone and watch as properties are acquired, improved, and operated. As properties generate cash flow, you could earn money through quarterly dividend payments. And over time, you could earn money off the potential appreciation of the properties.

So if you want to get started in the world of real-estate investing, it takes just a few minutes to sign up and create an account with the Fundrise Flagship Fund.

This is a paid advertisement. Carefully consider the investment objectives, risks, charges and expenses of the Fundrise Real Estate Fund before investing. This and other information can be found in the Fund’s prospectus. Read them carefully before investing.

4. Earn Up to $50 this Month By Answering Survey Questions About the News — It’s Anonymous

The news is a heated subject these days. It’s hard not to have an opinion on it.

Good news: A website called YouGov will pay you up to $50 or more this month just to answer survey questions about politics, the economy, and other hot news topics.

Plus, it’s totally anonymous, so no one will judge you for that hot take.

When you take a quick survey (some are less than three minutes), you’ll earn points you can exchange for up to $50 in cash or gift cards to places like Walmart and Amazon. Plus, Penny Hoarder readers will get an extra 500 points for registering and another 1,000 points after completing their first survey.

It takes just a few minutes to sign up and take your first survey, and you’ll receive your points immediately.

5. Get Up to $300 Just for Setting Up Direct Deposit With This Account

If you bank at a traditional brick-and-mortar bank, your money probably isn’t growing much (c’mon, 0.40% is basically nothing).

But there’s good news: With SoFi Checking and Savings (member FDIC), you stand to gain up to a hefty 3.80% APY on savings when you set up a direct deposit or have $5,000 or more in Qualifying Deposits and 0.50% APY on checking balances — savings APY is 10 times more than the national average.

Right now, a direct deposit of at least $1K not only sets you up for higher returns but also brings you closer to earning up to a $300 welcome bonus (terms apply).

You can easily deposit checks via your phone’s camera, transfer funds, and get customer service via chat or phone call. There are no account fees, no monthly fees and no overdraft fees. And your money is FDIC insured (up to $3M of additional FDIC insurance through the SoFi Insured Deposit Program).

It’s quick and easy to open an account with SoFi Checking and Savings (member FDIC) and watch your money grow faster than ever.

Read Disclaimer

5. Stop Paying Your Credit Card Company

If you have credit card debt, you know. The anxiety, the interest rates, the fear you’re never going to escape… but a website called AmONE wants to help.

If you owe your credit card companies $100,000 or less, AmONE will match you with a low-interest loan you can use to pay off every single one of your balances.

The benefit? You’ll be left with one bill to pay each month. And because personal loans have lower interest rates (AmONE rates start at 6.40% APR), you’ll get out of debt that much faster.

It takes less than a minute and just 10 questions to see what loans you qualify for.

6. Lock In Affordable Term Life Insurance in Minutes.

Let’s be honest—life insurance probably isn’t on your list of fun things to research. But locking in a policy now could mean huge peace of mind for your family down the road. And getting covered is actually a lot easier than you might think.

With Best Money’s term life insurance marketplace, you can compare top-rated policies in minutes and find coverage that works for you. No long phone calls. No confusing paperwork. Just straightforward quotes, starting at just $7 a month, from trusted providers so you can make an informed decision.

The best part? You’re in control. Answer a few quick questions, see your options, get coverage up to $3 million, and choose the coverage that fits your life and budget—on your terms.

You already protect your car, your home, even your phone. Why not make sure your family’s financial future is covered, too? Compare term life insurance rates with Best Money today and find a policy that fits.

Profile photo for Mark Hetherington

Practically speaking: pick a library implementation for (de)serializing JSON, e.g. GSON, then read its documentation. Don’t write code for it yourself unless truly necessary.

But let’s suppose that you’re not allowed a library; if we have to roll our own, we’ll try to make use of Java’s base interfaces for ease of development.

I’d start by considering the data structure. JSON is analogous to Map, where the keys are strings and the values can be various types, including other JSON objects. This implies recursion. So I’d start by creating a class:

  1. public class JSONObject<T> implements Map<String, T 

Practically speaking: pick a library implementation for (de)serializing JSON, e.g. GSON, then read its documentation. Don’t write code for it yourself unless truly necessary.

But let’s suppose that you’re not allowed a library; if we have to roll our own, we’ll try to make use of Java’s base interfaces for ease of development.

I’d start by considering the data structure. JSON is analogous to Map, where the keys are strings and the values can be various types, including other JSON objects. This implies recursion. So I’d start by creating a class:

  1. public class JSONObject<T> implements Map<String, T> 

Now we have a problem: we need to have a type for T that can either be another JSONObject or a data object at the “bottom” of such a structure. So let’s define a type that acts like a JSONObject but contains exactly one item:

  1. public class JSONData<T> extends JSONObject<T> implements Map.Entry<String, T> 

Note that we extend both Map and Map.Entry; that’s a bit odd, but it should work fine for a map with strictly one entry. We’ll probably have to throw UnsupportedOperationExceptions for some Map methods, but that’s fair where those methods are documented as optional.

With JSONData<T> set up, each of our items will either be a JSONObject<JSONObject>, or a JSONData<T>, where T is one of the basic types available to JSON, with primitives boxed: String, Float (JavaScript has only floating-point numbers), Boolean, or Object (that last one just to support null).

“But wait,” you say, “what about arrays?” Uh, oh, we’re missing an option. And since JavaScript’s array elements can be of mixed types, we have to account for the possibility. We’re going to end up with another class:

  1. public class JSONArray extends JSONObject<JSONObject> implements List<JSONObject> 

It’s a fudge again, because JSONData objects in a JSONArray have to have String keys when they probably ought to strictly have Integer ones, but we can just use the toString() method from Integer to make those.

Now that we support all the structural elements, we can write a static deserializer in JSONObject that splits by commas, ignoring ones inside brackets or braces, into a list of items, and recursively deserializes that list, using a factory method that produces JSONObject, JSONData, or JSONArray sub-elements as appropriate (brackets means an array, braces mean an object, neither means data); here’s the signature:

  1. public static JSONObject<JSONObject> deserialize(String serialized) 

Clever people might notice that I’ve got a key bit missing here: I probably want to create one or more Exception classes along the lines of MalformedJSONException or similar, and cause deserialize(String) to throw it if the input String is invalid.

That done, we can traverse the whole structure as a nested group of Map<String, Map> objects, and use instanceof JSONArray or instanceof JSONData on specific objects to help handle those. Naturally, the rest of your code would have to specify what sort of logic to use when traversing the data, but this is enough to make it traversable without assuming a particular schema for the JSON.

TL;DR: to do it manually, do a lot of needless work and debugging. Use a library.

Profile photo for Quora User

Just my thought:

Create your POJO with an overloaded constructor that can:

  1. Accept the JSON String and populate the fields.
  2. Accept JSONObject and populate the fields.

Create two accessors:

  1. One that can build a JSONObject from the fields.
  2. One that calls the above and overrides toString() to return a JSON String.
    1. I'd call #1 to get the Object and simply use toString(true) for formatted JSON strings

Everything else would be private. This insures everything is encapsulated.

Me, from a readability standpoint would create an interface, an abstract class that suites my general purpose needs and then any concre

Just my thought:

Create your POJO with an overloaded constructor that can:

  1. Accept the JSON String and populate the fields.
  2. Accept JSONObject and populate the fields.

Create two accessors:

  1. One that can build a JSONObject from the fields.
  2. One that calls the above and overrides toString() to return a JSON String.
    1. I'd call #1 to get the Object and simply use toString(true) for formatted JSON strings

Everything else would be private. This insures everything is encapsulated.

Me, from a readability standpoint would create an interface, an abstract class that suites my general purpose needs and then any concrete classes I may need.

Profile photo for Metis Chan

With today’s modern day tools there can be an overwhelming amount of tools to choose from to build your own website. It’s important to keep in mind these considerations when deciding on which is the right fit for you including ease of use, SEO controls, high performance hosting, flexible content management tools and scalability. Webflow allows you to build with the power of code — without writing any.

You can take control of HTML5, CSS3, and JavaScript in a completely visual canvas — and let Webflow translate your design into clean, semantic code that’s ready to publish to the web, or hand off

With today’s modern day tools there can be an overwhelming amount of tools to choose from to build your own website. It’s important to keep in mind these considerations when deciding on which is the right fit for you including ease of use, SEO controls, high performance hosting, flexible content management tools and scalability. Webflow allows you to build with the power of code — without writing any.

You can take control of HTML5, CSS3, and JavaScript in a completely visual canvas — and let Webflow translate your design into clean, semantic code that’s ready to publish to the web, or hand off to developers.

If you prefer more customization you can also expand the power of Webflow by adding custom code on the page, in the <head>, or before the </head> of any page.

Get started for free today!

Trusted by over 60,000+ freelancers and agencies, explore Webflow features including:

  • Designer: The power of CSS, HTML, and Javascript in a visual canvas.
  • CMS: Define your own content structure, and design with real data.
  • Interactions: Build websites interactions and animations visually.
  • SEO: Optimize your website with controls, hosting and flexible tools.
  • Hosting: Set up lightning-fast managed hosting in just a few clicks.
  • Grid: Build smart, responsive, CSS grid-powered layouts in Webflow visually.

Discover why our global customers love and use Webflow | Create a custom website.

Profile photo for Gabor Jakab

Interesting question. toString() is a method in java.lang.Object. It is possible to invoke toString() on any JSONObject like it is possible to invoke toString() on any other Java Object. For example:

jakarta.json.JsonObject (ex javax.json.JsonObject):

  1. JsonObject jsonObject = Json.createObjectBuilder() 
  2. .add("userName", "myUserName") 
  3. .add("email", "myEmailAddress@myDomain.com") 
  4. .add("address", Json.createObjectBuilder() 
  5. .add("city", "MyCity") 
  6. .add("zip", "33010")) 
  7. .build(); 
  8. System.out.println("JsonObject: "+jsonObject.toString()); 

org.json.JSONObject

  1. Map<Stri 

Interesting question. toString() is a method in java.lang.Object. It is possible to invoke toString() on any JSONObject like it is possible to invoke toString() on any other Java Object. For example:

jakarta.json.JsonObject (ex javax.json.JsonObject):

  1. JsonObject jsonObject = Json.createObjectBuilder() 
  2. .add("userName", "myUserName") 
  3. .add("email", "myEmailAddress@myDomain.com") 
  4. .add("address", Json.createObjectBuilder() 
  5. .add("city", "MyCity") 
  6. .add("zip", "33010")) 
  7. .build(); 
  8. System.out.println("JsonObject: "+jsonObject.toString()); 

org.json.JSONObject

  1. Map<String, Object> map = new HashMap<String, Object>(); 
  2. map.put("UUID", generateUUID()); 
  3. JSONObject jsonObject = new JSONObject(map); 
  4. System.out.println(jsonObject.toString()); 
Profile photo for Scott Brickner

Deserializing arbitrary JSON in Java doesn’t have any choice but to represent it so that JSON objects are deserialized as Map<Object>.

If you’re trying to deserialize to an actual type, like a User, then there are only two possibilities when you encounter an unknown field—either you’re deserializing an unknown subclass of User (in which case, you should throw the unknown property away) or you’re mistaken in thinking you were deserializing a User in the first place, in which case you should raise an exception.

Which of those two cases applies depends on the context. It’s a design decision somebod

Deserializing arbitrary JSON in Java doesn’t have any choice but to represent it so that JSON objects are deserialized as Map<Object>.

If you’re trying to deserialize to an actual type, like a User, then there are only two possibilities when you encounter an unknown field—either you’re deserializing an unknown subclass of User (in which case, you should throw the unknown property away) or you’re mistaken in thinking you were deserializing a User in the first place, in which case you should raise an exception.

Which of those two cases applies depends on the context. It’s a design decision somebody has to make.

Discover instant and clever code completion, on-the-fly code analysis, and reliable refactoring tools.
Profile photo for Hanumantha Reddy

convert a JSON object to a custom C# object is called as “Deserialization”.

Deserialization is the reading back in from the same types of storage you saved on a hard-disk, or by internet protocols, or other protocols , refresh the state of existing objects by setting their properties, field, etc.

Or you may deserialize to completely re-create classes, user interfaces, and code, instances of classes, values for properties, fields, etc.

Here we use DeserializeObject generic method with JsonConvert class to do deserialization.

We use “NewtonSoft.Json library” to convert from JSON to C# object.

Follow

convert a JSON object to a custom C# object is called as “Deserialization”.

Deserialization is the reading back in from the same types of storage you saved on a hard-disk, or by internet protocols, or other protocols , refresh the state of existing objects by setting their properties, field, etc.

Or you may deserialize to completely re-create classes, user interfaces, and code, instances of classes, values for properties, fields, etc.

Here we use DeserializeObject generic method with JsonConvert class to do deserialization.

We use “NewtonSoft.Json library” to convert from JSON to C# object.

Follow below videos to understand more on how to deserialize JSON to C# object.

Profile photo for Ashutosh Jha

If you using spring then @Requestbody take the responsibility to map json to pojo.

If you want manually you have 2ways

  1. Gson
  2. ObjectMapper

But in all cases you need to take care, json key shoud be same as pojo variable name.

Profile photo for Mariusz Kasolik

Yes, Java object can be serialized to JSON object and back. You can use Jackson library to accomplish this: FasterXML/jackson.

Profile photo for K Karthik

Convert an object into json/bytes called serialization and vice versa is deserialization ,which helps you to store, transfer object over the network.

Profile photo for Nicolae Marasoiu

It is Serializable so all that is needed is to use the Object Output Stream in order to serialize it, more details in Serialization and Deserialization in Java with Example

Alternatively, calling the writeObject method also does it.

Java serializing is not efficient. This is why in production where some performance cost ratio is required, various replacements can be used, that either are a drop in replacement or have a different API.

Profile photo for Gupteshwar Chand

JSON is yet another but most widely used format for transmitting data over the network.You can serialize your Java/C# class to JSON and deserialize JSON back to your class.Json appears in form of key/value pairs and it is very simple to understand for any client consuming it thanks to plethora of open source libraries. With restful services becoming a buzz, Json is becoming a standard.

Profile photo for David Roldán Martínez

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

Profile photo for Biranchi Narayan Padhi

Hello Buddy,

You can use Built in Function Provided by Python and convert it to dictionary directly.Now, you can use this if you do not know the Format of the Incoming JSON.

  1. import json  
  2.  
  3. # Opening JSON file  
  4. with open('data.json') as json_file:  
  5. data = json.load(json_file) 
  6.  
  7. #printing the data as Dicti 
  8. print(data) 
  9.  
  10. #printing the type of Data Variable: 
  11. print(type(data)) #it will print the class Dict as the json is already converted to dictionary, you can verify using this Method 

Now, if you know the Format of the incoming JSON Object , you can loop through it and easily make a Dictionary of your own witho

Hello Buddy,

You can use Built in Function Provided by Python and convert it to dictionary directly.Now, you can use this if you do not know the Format of the Incoming JSON.

  1. import json  
  2.  
  3. # Opening JSON file  
  4. with open('data.json') as json_file:  
  5. data = json.load(json_file) 
  6.  
  7. #printing the data as Dicti 
  8. print(data) 
  9.  
  10. #printing the type of Data Variable: 
  11. print(type(data)) #it will print the class Dict as the json is already converted to dictionary, you can verify using this Method 

Now, if you know the Format of the incoming JSON Object , you can loop through it and easily make a Dictionary of your own without any Built in Methods.

For Example if your JSON looks something like this:

JSON={

“AGE”:23,

“Inocme”:100000,

“Height”:6

}

You can make your dictionary writing Python Logic:

  1. print(type(JSON)) #this will print the type as JSON Object 
  2. Dicti={} 
  3. for key in JSON: 
  4. Dicti[key]=JSON[Key] 
  5.  
  6. print(type(Dicti)) #this will print the type of Object as Dictionary. 

Hope that helped you in some way to understand .Give it a Thumbs Up!!!

Adios!!

Profile photo for Alan Mellor

Use something like Google GSON or the Jackson library to turn a Java object into a JSON String. And back again.

Profile photo for Martin Gainty

When you serialise a JSON formatted data stream to storage

  1. [JsonConverter(typeof(DictionaryWrapperConverter))] 
  2. class MyWrapper : IEnumerable 
  3. { 
  4. Dictionary<string, string> values = new Dictionary<string, string>(); 
  5.  
  6. public void Add(string key, string value) 
  7. { 
  8. values.Add(key, value); 
  9. } 
  10.  
  11. IEnumerator IEnumerable.GetEnumerator() 
  12. { 
  13. return values.GetEnumerator(); 
  14. } 
  15. } 
  16.  
  17. class Program 
  18. { 
  19. static void Main(string[] args) 
  20. { 
  21. MyWrapper wrapper = new MyWrapper(); 
  22. wrapper.Add("foo", "bar"); 
  23. wrapper.Add("fizz", "bang"); 
  24.  
  25. // serialize single wrapper instan 

When you serialise a JSON formatted data stream to storage

  1. [JsonConverter(typeof(DictionaryWrapperConverter))] 
  2. class MyWrapper : IEnumerable 
  3. { 
  4. Dictionary<string, string> values = new Dictionary<string, string>(); 
  5.  
  6. public void Add(string key, string value) 
  7. { 
  8. values.Add(key, value); 
  9. } 
  10.  
  11. IEnumerator IEnumerable.GetEnumerator() 
  12. { 
  13. return values.GetEnumerator(); 
  14. } 
  15. } 
  16.  
  17. class Program 
  18. { 
  19. static void Main(string[] args) 
  20. { 
  21. MyWrapper wrapper = new MyWrapper(); 
  22. wrapper.Add("foo", "bar"); 
  23. wrapper.Add("fizz", "bang"); 
  24.  
  25. // serialize single wrapper instance 
  26. string json = JsonConvert.SerializeObject(wrapper, Formatting.Indented); 
  27. } 
  28. } 
Profile photo for Paul Lautman

Let me ask you a similar question. How do you map the french language to a car? Of course you don't since one is a language and the other is a physical object. Likewise SQL is a language and JSON is an object. They are not compatible. Not sure where the Java comes into it either.

Profile photo for Mitesh Pathak

I have worked with both Jackson and Gson.

For complex objects you still need to write serializers in Gson.

Your best bet would be using Gson for serializing from POJO to JSON.

If you are considering to serialize a POJO to bytes, I recommend using Kryo.

Profile photo for Ankit Gupta

Json is a file format and stand for Java Script Object Notation. It is commonly used for transferring the data over internet in REST protocols.

It is language independent format. Can be save any file with the extension “.json”. It is very light file as compared to .txt and .xml file and data read and write into file is very easy as compared to other formats.

Profile photo for Michał Kudela

There is a library called Gson. It is used for just that

It’s also bidirectional, so you can as easily convert json to object as to convert an object to json.

Profile photo for Tobias Kommerell

The best I could come up with is this:

deserialising subclasses with jackson

  1. package main; 
  2.  
  3. import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 
  4. import com.fasterxml.jackson.core.JsonProcessingException; 
  5. import com.fasterxml.jackson.databind.ObjectMapper; 
  6.  
  7. import java.io - enthusiast about java & open-source?.IOException; 
  8. import java.lang.reflect.InvocationTargetException; 
  9. import java.lang.reflect.Method; 
  10. import java.util.Arrays; 
  11.  
  12. abstract class Parent { 
  13.  
  14. public String getType(){ 
  15. return this.getClass().getCanonicalName(); 
  16. } 
  17.  
  18. String serialize() throws JsonProcessingException { return  

The best I could come up with is this:

deserialising subclasses with jackson

  1. package main; 
  2.  
  3. import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 
  4. import com.fasterxml.jackson.core.JsonProcessingException; 
  5. import com.fasterxml.jackson.databind.ObjectMapper; 
  6.  
  7. import java.io - enthusiast about java & open-source?.IOException; 
  8. import java.lang.reflect.InvocationTargetException; 
  9. import java.lang.reflect.Method; 
  10. import java.util.Arrays; 
  11.  
  12. abstract class Parent { 
  13.  
  14. public String getType(){ 
  15. return this.getClass().getCanonicalName(); 
  16. } 
  17.  
  18. String serialize() throws JsonProcessingException { return new ObjectMapper().writeValueAsString(this);} 
  19. } 
  20.  
  21. @JsonIgnoreProperties(ignoreUnknown = true) 
  22. class Son extends Parent { 
  23. static Parent deserialize(String json) throws IOException { 
  24. return new ObjectMapper().readValue(json, Son.class); 
  25. } 
  26. } 
  27.  
  28. @JsonIgnoreProperties(ignoreUnknown = true) 
  29. class Daughter extends Parent { 
  30. static Parent deserialize(String json) throws IOException { 
  31. return new ObjectMapper().readValue(json, Daughter.class); 
  32. } 
  33. } 
  34.  
  35. public class run { 
  36. public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, IOException { 
  37. Parent[] events = new Parent[]{new Daughter(), new Son(), new Daughter(), new Son() }; 
  38. String[] serialisedEvents = new String[events.length]; 
  39.  
  40. for(int i = 0; i < events.length; i++){ 
  41. serialisedEvents[i] = events[i].serialize(); 
  42. } 
  43.  
  44. Parent[] deserialisedEvents = new Parent[events.length]; 
  45.  
  46. for(int i = 0; i < events.length; i++){ 
  47. String typeName = new ObjectMapper().readTree(serialisedEvents[i]).get("type").textValue(); 
  48. final Method deserialize = Class.forName(typeName).asSubclass(Parent.class).getDeclaredMethod("deserialize", new Class[]{String.class}); 
  49. int j = deserialize.getParameterCount(); 
  50. final Class<?>[] parameterTypes = deserialize.getParameterTypes(); 
  51. deserialisedEvents[i] = (Parent) deserialize.invoke(null, serialisedEvents[i]); 
  52. } 
  53. System.out.printf("events:\n%s%n", Arrays.toString(events)); 
  54. System.out.printf("serialized events:\n%s%n", Arrays.toString(serialisedEvents)); 
  55. System.out.printf("deserialized events:\n%s%n", Arrays.toString(deserialisedEvents)); 
  56.  
  57. } 
  58. } 
Profile photo for SuneetPadhi

If you want to add a serializer then use @JsonSerialize(using = className.class) or you need to use object mapper to create a serializer.

Profile photo for Vivek Singh Yadav

You can use a DTO class wirh multiple data structures as members and later you can convert them to json using gson.

Profile photo for Abu Sufyan
  1. ObjectMapper mapper = new ObjectMapper(); 
  2. HashMap<String,Object> result = 
  3. mapper.readValue(JSON_SOURCE, HashMap.class); 
Profile photo for Quora User

Create a new map.

Iterate through the loaded Properties and read the key/value pairs. Then load them into your map.

Profile photo for Kapil Soni

Using GSon , you can do the following:

Map < String , Object > retMap = new Gson ().

jsonString, new TypeToken < HashMap < Str

);

Profile photo for Tushar Girase

You can use GSON library for the same.

Profile photo for Robin Verlangen

With Google Gson it seems to work most of the time out of the box. The only thing is that it might get more tricky with complex data types. However primitives, arrays, lists or maps seem to work fine.

Profile photo for Philip Newton

Um, as you said: JSON text is text.

So you can just write it to a file.

‘Serialisation’ is mostly used in the context of binary objects which have to get transformed into text for storage or transmission (and back again, upon deserialisation). But JSON is already in text form.

It’s kind of like asking ‘how do I liquefy water?’.

About · Careers · Privacy · Terms · Contact · Languages · Your Ad Choices · Press ·
© Quora, Inc. 2025