I have Java string and would like to parse it to JSON file. I first try to parse the string to an Object then to Json Object. The java string contains array/list of 2 elements. I would want to maintain that structure since its submitted to an API in that form.
Content of my String looks as below:
[
{ "foedselsdato" : "2012-04-29",
"individId" : "052804211084",
"undergruppe" : "KU",
"varslinger" :
{ "medisinering" :
[
{ "merknad" : "",
"preparat" : "11 Mastipen vet Intramammarie 300 mg\/sprøyte",
"tilbakeholdelsesdato" : "2020-08-25" },
{ "merknad" : "",
"preparat" : "11 Penovet vet Inj væske, susp 300 mg\/ml",
"tilbakeholdelsesdato" : "2020-08-25" } ] } },
{ "foedselsdato" : "2017-05-19",
"individId" : "052820651335",
"undergruppe" : "KU",
"varslinger" :
{ "helsetilstand" :
[
{ "merknad" : "Ole test",
"tilstand" : "SVAK_HALTHET",
"tiltak" : "EKSTRA_STROE" } ] } } ]
Below is my code:
String Stringtojson = Concstring;
JSONParser parser = new JSONParser();
try
{
Object object = parser.parse(Stringtojson);
//convert Object to JSONObject
JSONObject jsonObject3 = (JSONObject)object;
try {
FileWriter file = new FileWriter("F:\myjson.json");
file.write(jsonObject3.toJSONString());
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
catch(Exception e)
{
e.printStackTrace();
}
class org.json.simple.JSONArray cannot be cast to class org.json.simple.JSONObjectalready tells you what the problem is: you get aJSONArraywhich is perfectly fine for your json string but you can't cast that toJSONObject. So just cast toJSONArrayinstead.