简体   繁体   中英

How to extract json string objects separately with Gson

I have the following json string:

String config = "{contact:{\"FIRSTNAME\":\"C_FirstName\",\"EMAIL\":\"C_EmailAddress\"}, "
                          + "customobject:{\"CUSTOM_FIELD1\":\"Custom_Field__11\","
                          + "\"FIRSTNAME\":\"First_Name1\",\"EMAIL\":\"Email_Address1\"}}";

I need to extract each object, ie, contact and customobject as a String so the final result should be:

String contact = "{\"FIRSTNAME\":\"C_FirstName\",\"EMAIL\":\"C_EmailAddress\"}";
String customobject = "{\"CUSTOM_FIELD1\":\"Custom_Field__11\","
                      + "\"FIRSTNAME\":\"First_Name1\",\"EMAIL\":\"Email_Address1\"}";

It is required to use Gson for this so I'm trying the following:

Map<String, String> map = gson.fromJson(config, new TypeToken<Map<String,Object>>(){}.getType());

 String json = map.get("contact").toString();

But I get the following error:

java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to java.lang.String

What is the proper way to achieve this ?

If you have simply to extract JSON property values, you don't need your deserialization and serialization steps. All you have to do here is making the JSON tree model out of your JSON input data and address the target objects. In Gson there are JsonElement s that serve this (and that) purpose.

private static final JsonParser jsonParser = new JsonParser();

public static void main(final String... args) {
    final String config = "{contact:{\"FIRSTNAME\":\"C_FirstName\",\"EMAIL\":\"C_EmailAddress\"}, "
            + "customobject:{\"CUSTOM_FIELD1\":\"Custom_Field__11\","
            + "\"FIRSTNAME\":\"First_Name1\",\"EMAIL\":\"Email_Address1\"}}";
    final JsonObject rootObject = jsonParser.parse(config).getAsJsonObject();
    System.out.println(rootObject.get("contact"));
    System.out.println(rootObject.get("customobject"));
}

Output:

{"FIRSTNAME":"C_FirstName","EMAIL":"C_EmailAddress"}
{"CUSTOM_FIELD1":"Custom_Field__11","FIRSTNAME":"First_Name1","EMAIL":"Email_Address1"}

Every JsonElement subclass has its own toString() implementation to produce its JSON string representation. Please see Gson JsonElement and JsonParser JavaDocs for the details.

Found my solution:

import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

public class JsonTest {


    static String config = "{contact:{\"FIRSTNAME\":\"C_FirstName\",\"EMAIL\":\"C_EmailAddress\"}, "
                          + "customobject:{\"CUSTOM_FIELD1\":\"Custom_Field__11\","
                          + "\"FIRSTNAME\":\"First_Name1\",\"EMAIL\":\"Email_Address1\"}}";

    String contact = "{\"FIRSTNAME\":\"C_FirstName\",\"EMAIL\":\"C_EmailAddress\"}";
    String customobject = "{\"CUSTOM_FIELD1\":\"Custom_Field__11\","
                          + "\"FIRSTNAME\":\"First_Name1\",\"EMAIL\":\"Email_Address1\"}";

    public static void main(String[] args) {

        Gson gson = new Gson();

        Conf c = gson.fromJson(config, Conf.class);

        String contactStr = gson.toJson(c.getContact());

        System.out.println(contactStr);

    }

    class Conf{

        Map<String, String> contact;
        Map<String, String> co;
        public Map<String, String> getContact() {
            return contact;
        }
        public void setContact(Map<String, String> contact) {
            this.contact = contact;
        }
        public Map<String, String> getCo() {
            return co;
        }
        public void setCo(Map<String, String> co) {
            this.co = co;
        }


    }
}

Try This

  1. Create Class Config, Contact And CustomObject As Given Below

     class Config implements Serializable { Contact contact; CustomObject customobject; public Config() { this(new Contact("",""), new CustomObject("", "", "")); } public Config(Contact contact, CustomObject customobject) { this.contact = contact; this.customobject = customobject; } public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } public CustomObject getCustomobject() { return customobject; } public void setCustomobject(CustomObject customobject) { this.customobject = customobject; } } class Contact implements Serializable{ String FIRSTNAME; String EMAIL; public Contact() { this("",""); } public Contact(String FIRSTNAME, String EMAIL) { this.FIRSTNAME = FIRSTNAME; this.EMAIL = EMAIL; } public String getEMAIL() { return EMAIL; } public void setEMAIL(String EMAIL) { this.EMAIL = EMAIL; } public String getFIRSTNAME() { return FIRSTNAME; } public void setFIRSTNAME(String FIRSTNAME) { this.FIRSTNAME = FIRSTNAME; } } class CustomObject implements Serializable { String CUSTOM_FIELD1; String FIRSTNAME; String EMAIL; public CustomObject() { this("", "", ""); } public CustomObject(String CUSTOM_FIELD1, String FIRSTNAME, String EMAIL) { this.CUSTOM_FIELD1 = CUSTOM_FIELD1; this.FIRSTNAME = FIRSTNAME; this.EMAIL = EMAIL; } public String getCUSTOM_FIELD1() { return CUSTOM_FIELD1; } public void setCUSTOM_FIELD1(String CUSTOM_FIELD1) { this.CUSTOM_FIELD1 = CUSTOM_FIELD1; } public String getFIRSTNAME() { return FIRSTNAME; } public void setFIRSTNAME(String FIRSTNAME) { this.FIRSTNAME = FIRSTNAME; } public String getEMAIL() { return EMAIL; } public void setEMAIL(String EMAIL) { this.EMAIL = EMAIL; } } 
  2. Now Parse It Using GSON As Below

     String config = "{contact {\\"FIRSTNAME\\":\\"C_FirstName\\",\\"EMAIL\\":\\"C_EmailAddress\\"}, " + "customobject:{\\"CUSTOM_FIELD1\\":\\"Custom_Field__11\\"," + "\\"FIRSTNAME\\":\\"First_Name1\\",\\"EMAIL\\":\\"Email_Address1\\"}}"; try { Gson gson = new Gson(); Config config1 = gson.fromJson(config, Config.class); System.out.println(config1.getContact().FIRSTNAME); System.out.println(config1.getContact().EMAIL); System.out.println(config1.getCustomobject().CUSTOM_FIELD1); System.out.println(config1.getCustomobject().FIRSTNAME); System.out.println(config1.getCustomobject().EMAIL); } catch (JsonSyntaxException e) { e.printStackTrace(); } 

NOTE : Please Follow Best Practices For Naming Conventions. You are using wrong one.

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