[Java] Try editing the elements of the Json string using the library

Thing you want to do

String jsonString = "{\"Apple\":{" 
						+ "\"cost\":\"0\"},"
					+ "\"Pen\":{"
						+ "\"cost\":\"0\"}}";

I want to do the following two points.

This time, I will use the following library for operating typical (?) Json.

Execution environment

Android Studio: 3.4.1 gradle: 5.1.1

Library addition

Describe the library to be added in the dependencies block of build.gradle.

dependencies {
	...
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.9.8'
    implementation 'org.glassfish:javax.json:1.1.4'
}

Gson Create Json string with the created method (editJson) Replaced with Map <String, MAP <String, String >> (Gson.fromJson) and assigned the desired key and value. After the substitution, the Map is converted back to a Json string (Gson.toJson).

Although it deviates from the main subject, Convert [Json => other class] to "Deserialization", The conversion of [other class => Json] is called "Serialization".

import com.google.gson.Gson;
...

public class GsonExample {

	String jsonString = "{\"Apple\":{" +
							"\"cost\":\"0\"}," +
						"\"Pen\":{" + 
							"\"cost\":\"0\"}}";
	
	public void main() {
		editJson("Apple", "100");
		/*
			{
				"Apple": {
					"cost": "100"
				},
				"Pen": {"
					"cost": "0"
				}
			}"
		*/
		editJson("ApplePen", "");
		/*
			{
				"Apple": {
					"cost": "100"
				},
				"Pen": {"
					"cost": "0"
				}
				"ApplePen": {"
					"cost": "0"
				}
			}"
		*/
	}

	private void editJson(String key, String str) {
		if (str.isEmpty()) str = "0";
        Map<String, String> innerMap = new HashMap<>();
        innerMap.put("cost", str);

    	Gson gson = new Gson();
    	//Convert Json string to Map
        Map<String, Map<String,String>> jsonMap = gson.fromJson(jsonString, Map.class);
        jsonMap.put(key, innerMap);
    	//Convert Map to Json string again
        jsonString = gson.toJson(jsonMap);
    }
}

Jackson The replacement process is performed in almost the same way as for Gson. Jackson translates Json via the ╩╗ObjectMapper` method.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
...

public class JacksonExample {
	// main()Is omitted

    private void editJson(String str, String key) {
		if (str.isEmpty()) str = "0";
        Map<String, Object> map = null;
        Map<String, String> innerMap = new HashMap<>();
        innerMap.put("cost", str);

        ObjectMapper mapper = new ObjectMapper();
        try {
        	//Convert Json string to Map
            map = mapper.readValue(json, 
									new TypeReference<Map<String, Object>>() {});
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put(key, innerMap);
        try {
        	//Convert Map to Json string again
            json = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
	}
}

About javax.json

I tried to implement the same with the javax.json library, but I got stuck.

Impressions

20.09.27 postscript (about org.json.JSONObject)

I realized that if you just want to convert Json to Map and add a value, you can use ╩╗org.json.JSONObject`.

import org.json.JSONException;
import org.json.JSONObject;
...

public class JSONExample {
	// main()Is omitted

    private void editJson(String str, String key) {
		if (str.isEmpty()) str = "0";
        Map<String, String> innerMap = new HashMap<>();
        innerMap.put("cost", str);
        try {
            JSONObject jsonObject = new JSONObject(json);
            jsonObject.put(key, new JSONObject(innerMap));
            json = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

References

I referred to the following article.

Recommended Posts

[Java] Try editing the elements of the Json string using the library
Parse and objectize JSON using the @JsonProperty annotation of the Java library Jackson
Try global hooking in Java using the JNativeHook library
[Java] Delete the elements of List
Try using || instead of the ternary operator
Examine the memory usage of Java elements
Try using the Stream API in Java
Try using JSON format API in Java
Compare the elements of an array (Java)
Try using the Wii remote with Java
[Java] How to get to the front of a specific string using the String class
The story of low-level string comparison in Java
[Java] Get the length of the surrogate pair string
[Java] The confusing part of String and StringBuilder
Try similar search of Image Search using Java SDK [Search]
Try accessing the dataset from Java using JZOS
Try the free version of Progate [Java II]
Try using the COTOHA API parsing in Java
Try the free version of Progate [Java I]
Try adding text to an image in Scala using the Java standard library
[Java] How to easily get the longest character string of ArrayList using stream
Summarize the additional elements of the Optional class in Java 9
Try using the query attribute of Ruby on Rails
[Note] Java Output of the sum of odd and even elements
Try using RocksDB in Java
Try scraping using java [Notes]
Check the status of Java application without using monitoring tool
The story of pushing Java to Heroku using the BitBucket pipeline
I tried using the CameraX library with Android Java Fragment
[Java] Try to solve the Fizz Buzz problem using recursive processing
The story of not knowing the behavior of String by passing Java by reference
Try Hello World with the minimum configuration of Heroku Java spring-boot
Try using the two-point measurement function of Firebase Performance Monitoring. [Android]
Try passing values from Java Servlet to iPhone app using JSON
I tried to summarize the methods of Java String and StringBuilder
How to check for the contents of a java fixed-length string
Is the version of Elasticsearch you are using compatible with Java 11?
[Java] Speed comparison of string concatenation
Various methods of Java String class
[Java version] The story of serialization
Java comparison using the compareTo () method
Try using Redis with Java (jar)
Handling of time zones using Java
Various methods of the String class
Welcome to the Java Library Swamp! !!
[Java] Try to implement using generics
Try using the messaging system Pulsar
Try using IBM Java method tracing
[Java] Correct comparison of String type
Summary of object-oriented programming using Java
I read the source of String
The origin of Java lambda expressions
Try using Hyperledger Iroha's Java SDK
[Java] Where did you try using java?
I tried using GoogleHttpClient of Java
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
[Java] Check if the character string is composed only of blanks (= Blank)
Display Japanese calendar and days of the week using java8 standard class
Try using Java framework Nablarch [Web application]
Get the result of POST in Java
Check the contents of the Java certificate store