Uguqula njani imephu yeJava iye kwiJSON

Zininzi iindlela zokuguqula iMephu yeJava ibe yiJSON. Kuqhelekile ukuguqula iiJava Arrows kunye neeMephu zibe yiJSON kwaye ngokuchaseneyo.

Kule posi, sijonga imizekelo emi-3 eyahlukeneyo yokuguqula iMephu yeJava ibe yiJSON. Siza kusebenzisa amathala eencwadi kaJackson, uGson kunye no-org.



Imephu yeJava eya kwiJSON isebenzisa uJackson

Lo mzekelo ulandelayo usebenzisa uJackson Core kunye noJackson Binding ukuguqula iMephu yeJava ibe yiJSON.


Ukuze sisebenzise amathala eencwadi kaJackson, kuqala kufuneka sizongeze kuthi pom.xml ifayile:



com.fasterxml.jackson.core

jackson-core
2.9.8


com.fasterxml.jackson.core
jackson-databind
2.9.8

Emva koko:


import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; public class ConvertJavaMapToJson {
@Test
public void convertMapToJson() {
Map elements = new HashMap();
elements.put('Key1', 'Value1');
elements.put('Key2', 'Value2');
elements.put('Key3', 'Value3');

ObjectMapper objectMapper = new ObjectMapper();

try {

String json = objectMapper.writeValueAsString(elements);

System.out.println(json);
} catch (JsonProcessingException e) {

e.printStackTrace();
}
} }

Iziphumo:

{'Key2':'Value2','Key1':'Value1','Key3':'Value3'}

Njengoko kunokubonwa kwimveliso, iodolo yezinto kwiJSON ayifani nomyalelo esiwongeze kwimephu.

Ukugcina iodolo, kufuneka sisebenzise SortedMap endaweni yoko.

umz.


SortedMap elements = new TreeMap();

Iziphumo:

{'Key1':'Value1','Key2':'Value2','Key3':'Value3'}

Idibeneyo:



Imephu yeJava eya kwiJSON isebenzisa iGson

Lo mzekelo ulandelayo usebenzisa ilayibrari yeGson ukuguqula iMephu yeJava ibe yiJSON, kodwa kuqala, kufuneka songeze iGson njengokuxhomekeka | | + _ | ifayile.

pom.xml

Emva koko:




com.google.code.gson
gson
2.8.5

Iziphumo:

import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.junit.jupiter.api.Test; import java.lang.reflect.Type; import java.util.HashMap; import java.util.SortedMap; import java.util.TreeMap; public class ConvertJavaMapToJson {
@Test
public void convertMapToJson() {
SortedMap elements = new TreeMap();
elements.put('Key1', 'Value1');
elements.put('Key2', 'Value2');
elements.put('Key3', 'Value3');

Gson gson = new Gson();
Type gsonType = new TypeToken(){}.getType();
String gsonString = gson.toJson(elements,gsonType);
System.out.println(gsonString);
} }


Imephu yeJava eya kwiJSON isebenzisa i-org

Lo mzekelo ulandelayo usebenzisa ithala leencwadi le-org.json ukuguqula iMephu yeJava ibe yiJSON, kodwa kuqala, kufuneka songeze i-org.json njengokuxhomekeka | | ifayile.

{'Key1':'Value1','Key2':'Value2','Key3':'Value3'}

Emva koko:

pom.xml

Iziphumo:




org.json
json
20180813