简体   繁体   中英

Converting to JSon or any map type java

I have a string which looks like below.

Model [Name=Mobie , location= US, actualTransferDate=null, scanserialCode=234335,1237787, modelNum=MIC 898989 ]

Can i convert this to Json? Is it possible?So i have done like this below but it not working now.

List<String> invoicelist = Arrays.asList(checkeditems);
    String invocejson = new Gson().toJson(invoicelist);
    Map<String,String> map = new HashMap<String,String>();
    ObjectMapper mapper = new ObjectMapper();
    try {
        map = mapper.readValue(invocejson, new TypeReference<HashMap<String, String>>(){});
        log.info("****"+map);
    } catch (Exception e) {
        e.printStackTrace();
    }

If i can convert it could be easy for me to pass json to Jsp and then use it there.Can any one help me on this?

You can do something like this....

        //import org.json.simple.JSONObject;

            JSONObject object = new JSONObject();
    ArrayList<Integer> array = new ArrayList<Integer>();

    String model = "Model [Name=Mobie , location= US , actualTransferDate=null , scanserialCode=234335,1237787 , modelNum=MIC 898989 ]";
    String[] v = model.substring(5).replace("[" , "").replace("]" , "").split(" ,");
    for(int i = 0;i < v.length;i++){
        String[] j = v[i].split("=");
        switch (j[0]) {
        case " Name":
            object.put("Name",j[1]);
            break;
        case " location":
            object.put("location", "US");
            break;
        case " actualTransferDate":
            object.put("actualTransferDate",j[1]);
            break;
        case " scanserialCode":
            String[] l = j[1].split(",");
            array.add(Integer.parseInt(l[0]));
            array.add(Integer.parseInt(l[1]));
            object.put("scanserialCode", array);
            break;
        case " modelNum":
            object.put("modelNum",j[1]);
            break;

        default:
            break;
        }
    }
    System.out.print("JSON Output string : "+object);
}

OUTPUT:

JSON Output string : {"Name":"Mobie","actualTransferDate":"null","location":"US","modelNum":"MIC 898989 ","scanserialCode":[234335,1237787]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM