0

I have a LinkedHashMap and MyClass has 2 string variables I want to convert this to Json so that it can paresed in javascript Please share how to do this.

I have created this structure because i need to store the values of of table in the format of rowName, columnName and its value

Struture

Map<String,MyClass> dataMap = new LinkedHashMap<String,MyClass>();

MyClass{
String fieldName;
String fieldValue;
}
Ben McIntyre
  • 1,972
  • 17
  • 28

2 Answers2

0

You can use the Jackson 2 library.

An example you can find here (third part):

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class JacksonExample1 {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();

        Staff staff = createStaff();

        try {

            // Java objects to JSON file
            mapper.writeValue(new File("c:\\test\\staff.json"), staff);

            // Java objects to JSON string - compact-print
            String jsonString = mapper.writeValueAsString(staff);

            System.out.println(jsonString);

            // Java objects to JSON string - pretty-print
            String jsonInString2 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);

            System.out.println(jsonInString2);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static Staff createStaff() {

        Staff staff = new Staff();

        staff.setName("mkyong");
        staff.setAge(38);
        staff.setPosition(new String[]{"Founder", "CTO", "Writer"});
        Map<String, BigDecimal> salary = new HashMap() {{
            put("2010", new BigDecimal(10000));
            put("2012", new BigDecimal(12000));
            put("2018", new BigDecimal(14000));
        }};
        staff.setSalary(salary);
        staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));

        return staff;

    }

}

To resume you create an ObjectMapper then you can write an object to a file with mapper.writeValue or to a string with mapper.writeValueAsString.

Julien Rousé
  • 1,115
  • 1
  • 15
  • 30
-1

you can use a JSON library to do it. You can use the org.json library. This answer will help you Convert from LinkedHashMap to json string