Java создать json строку

Create JSON String using GSON

How can I make a JSON String with a field [At some point], without a field [at some point]. Any help will be highly appreciable. Thanks.

When you declare an int variable, its default value is 0. An int could not be null. So I advise you to use a String instead or to ignore the id value if it is 0.

5 Answers 5

Better is to use @expose annotation like

And use below method to get Json string from your object

private String getJsonString(Student student) < // Before converting to GSON check value of id Gson gson = null; if (student.id == 0) < gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create(); >else < gson = new Gson(); >return gson.toJson(student); > 

It will ignore id column if that is set to 0, either it will return json string with id field.

what if I have an Object as one of the properties of the class, and I have implemented Gson in that object?

You can explore the json tree with gson.

gson.toJsonTree(stu1).getAsJsonObject().remove("id"); 

You can add some properties also :

gson.toJsonTree(stu2).getAsJsonObject().addProperty("id", "100"); 
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(stu2); jsObj.remove("age"); // remove field 'age' jsObj.addProperty("key", "value"); // add field 'key' System.out.println(jsObj); 

You can manipulate with JsonObject

You should introduce additional field to Student class that will notice GSON about id serialization policy. Then, you should implement custom serializer that will implement TypeAdapter . In your TypeAdapter implementation according to id serialization policy you will serialize it or not. Then you should register your TypeAdapter in GSON factory:

GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(Student.class, new StudentTypeAdapter()); 
  • Use Java’s transient keyword which is to indicate that a field should not be serialized. Gson will exclude it automatically. This may not work for you as you want it conditionally.
  • Use @Expose annotation for the fields that you want and initialize your Gson builder as following: Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

So you need to mark name and age fields using @Expose and you need to have two different Gson instances for the default one which includes all fields and the one above which excludes fields without @Expose annotation.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Create JSON String using GSON

How can I make a JSON String with a field [At some point], without a field [at some point]. Any help will be highly appreciable. Thanks.

When you declare an int variable, its default value is 0. An int could not be null. So I advise you to use a String instead or to ignore the id value if it is 0.

5 Answers 5

Better is to use @expose annotation like

And use below method to get Json string from your object

private String getJsonString(Student student) < // Before converting to GSON check value of id Gson gson = null; if (student.id == 0) < gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create(); >else < gson = new Gson(); >return gson.toJson(student); > 

It will ignore id column if that is set to 0, either it will return json string with id field.

what if I have an Object as one of the properties of the class, and I have implemented Gson in that object?

You can explore the json tree with gson.

gson.toJsonTree(stu1).getAsJsonObject().remove("id"); 

You can add some properties also :

gson.toJsonTree(stu2).getAsJsonObject().addProperty("id", "100"); 
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(stu2); jsObj.remove("age"); // remove field 'age' jsObj.addProperty("key", "value"); // add field 'key' System.out.println(jsObj); 

You can manipulate with JsonObject

You should introduce additional field to Student class that will notice GSON about id serialization policy. Then, you should implement custom serializer that will implement TypeAdapter . In your TypeAdapter implementation according to id serialization policy you will serialize it or not. Then you should register your TypeAdapter in GSON factory:

GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(Student.class, new StudentTypeAdapter()); 
  • Use Java’s transient keyword which is to indicate that a field should not be serialized. Gson will exclude it automatically. This may not work for you as you want it conditionally.
  • Use @Expose annotation for the fields that you want and initialize your Gson builder as following: Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

So you need to mark name and age fields using @Expose and you need to have two different Gson instances for the default one which includes all fields and the one above which excludes fields without @Expose annotation.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to convert Java String to JSON Object

This question has been asked earlier, but I am unable to figure out the error in my code from the responses to those questions. I am trying to convert a java string into json object. Here is the code:

import org.json.JSONObject; //Other lines of code URL seatURL = new URL("http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2"); //Return the JSON Response from the API BufferedReader br = new BufferedReader(new InputStreamReader(seatURL.openStream(),Charset.forName("UTF-8"))); String readAPIResponse = " "; StringBuilder jsonString = new StringBuilder(); while((readAPIResponse = br.readLine()) != null) < jsonString.append(readAPIResponse); >JSONObject jsonObj = new JSONObject(jsonString); System.out.println(jsonString); System.out.println("---------------------------"); System.out.println(jsonObj); 

So, as you can see, the jsonstring is getting the data, but the jsonObj does not. I am using org.json JAR.

@Bohemian : The string was created dynamically from the URL. I am not sure, if there is any other class that represents it, other than plain String class.

@Gunaseelan : When I create JSON Object as shown in the link you mentioned, it works. However, my data for the object comes dynamically, and when I try to create the JSONObject dynamically, it fails.

5 Answers 5

You are passing into the JSONObject constructor an instance of a StringBuilder class.

This is using the JSONObject(Object) constructor, not the JSONObject(String) one.

JSONObject jsonObj = new JSONObject(jsonString.toString()); 

@Nishit, JSONObject does not natively understand how to parse through a StringBuilder; instead you appear to be using the JSONObject(java.lang.Object bean) constructor to create the JSONObject, however passing it a StringBuilder.

See this link for more information on that particular constructor.

When a constructor calls for a java.lang.Object class, more than likely it’s really telling you that you’re expected to create your own class (since all Classes ultimately extend java.lang.Object) and that it will interface with that class in a specific way, albeit normally it will call for an interface instead (hence the name) OR it can accept any class and interface with it «abstractly» such as calling .toString() on it. Bottom line, you typically can’t just pass it any class and expect it to work.

At any rate, this particular constructor is explained as such:

Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with «get» or «is» followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the «get» or «is» prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named «getName», and if the result of calling object.getName() is «Larry Fine», then the JSONObject will contain «name»: «Larry Fine».

So, what this means is that it’s expecting you to create your own class that implements get or is methods (i.e.

So, to solve your problem, if you really want that higher level of control and want to do some manipulation (e.g. modify some values, etc.) but still use StringBuilder to dynamically generate the code, you can create a class that extends the StringBuilder class so that you can use the append feature, but implement get/is methods to allow JSONObject to pull the data out of it, however this is likely not what you want/need and depending on the JSON, you might spend a lot of time and energy creating the private fields and get/is methods (or use an IDE to do it for you) or it might be all for naught if you don’t necessarily know the breakdown of the JSON string.

So, you can very simply call toString() on the StringBuilder which will provide a String representation of the StringBuilder instance and passing that to the JSONObject constructor, such as below:

. StringBuilder jsonString = new StringBuilder(); while((readAPIResponse = br.readLine()) != null) < jsonString.append(readAPIResponse); >JSONObject jsonObj = new JSONObject(jsonString.toString()); . 

Источник

Пример работы с JSON.org в Java: разбор и создание JSON

Обработка JSON с помощью orgJSON в Java

Эта статья является продолжением серии статей по работе с Json в Java. В прошлой статье мы разобрались с Json Simple API на примере, а в этой статье мы познакомимся с достаточно простым и удобным способом обработки Json в Java под названием JSON.org.

JSON.org — это одна из первых open source библиотек для работы с JSON в Java. Она достаточно проста в использовании, однако не является самой гибкой и быстрой из существующих.

Обзор библиотеки JSON.org

JSON.org содержит классы для разбора и создания JSON из обычной Java-строки. Также она имеет возможность преобразовывать JSON в XML, HTTP header, Cookies и многое другое.

Основу этой библиотеки составляют следующие классы:

  1. Класс org.json.JSONObject — хранит неупорядоченные пары типа ключ — значение. Значение могут быть типа String, JSONArray, JSONObject.NULL, Boolean и Number . Класс JSONObject также содержит конструкторы для конвертации Java-строки в JSON и дальнейшего ее разбора в последовательность ключ-значений.
  2. Класс org.json.JSONTokener используется для разбора JSON строки, а также используется внутри классов JSONObject и JSONArray
  3. Класс org.json.JSONArray хранит упорядоченную последовательность значений в виде массива JSON элементов.
  4. Класс org.json.JSONWriter представляет возможность получения Json. Он содержит такие полезные в работе методы, как append(String) — добавить строку в JSON текст, key(String) и value(String) методы для добавления ключа и значения в JSON строку. Также org.json.JSONWriter умеет записывать массив.
  5. org.json.CDL — этот класс содержит методы для преобразования значений, разделенных запятыми, в объекты JSONArray и JSONArray.
  6. Класс org.json.Cookie располагает методами для преобразования файлов cookie веб-браузера в JSONObject и обратно.
  7. Класс org.json.CookieList помогает преобразовать список куки в JSONObject и обратно.

Добавление библиотеки json.org в проект

Для удобства я использовал среду разработки Intellij IDEA Community Edition. Если Вы не хотите создавать maven проект, то можете создать простой проект и вручную добавить .jar библиотеку в проект. Создадим maven проект и добавим в зависимости библиотеку org.json. Фрагмент файла pom.xml с зависимостями у меня выглядит следующим образом:

Источник

Читайте также:  Visual programing in java
Оцените статью