source

다음 json 문자열을 java 개체로 변환하는 방법

goodcode 2022. 9. 5. 22:57
반응형

다음 json 문자열을 java 개체로 변환하는 방법

다음 JSON 문자열을 Java 개체로 변환합니다.

String jsonString = "{
  "libraryname": "My Library",
  "mymusic": [
    {
      "Artist Name": "Aaron",
      "Song Name": "Beautiful"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Oops I did It Again"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Stronger"
    }
  ]
}"

제 목표는 다음과 같이 쉽게 접속하는 것입니다.

(e.g. MyJsonObject myobj = new MyJsonObject(jsonString)
myobj.mymusic[0].id would give me the ID, myobj.libraryname gives me "My Library").

잭슨은 들어본 적이 있지만, 마이뮤직 리스트가 포함되어 있기 때문에 키밸류뿐만 아니라 제 json 스트링에 맞는 사용법을 잘 모르겠습니다.잭슨과 함께라면 어떻게 해야 할까요? 아니면 잭슨이 이 일에 적합하지 않다면 더 쉬운 방법이 있을까요?

이를 위해 GSON을 사용할 필요가 없습니다.잭슨은 플레인 맵/목록 중 하나를 수행할 수 있습니다.

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);

또는 보다 편리한 JSON 트리:

JsonNode rootNode = mapper.readTree(json);

참고로 실제로 Java 클래스를 만들어 IMO를 보다 편리하게 할 수 없는 이유는 없습니다.

public class Library {
  @JsonProperty("libraryname")
  public String name;

  @JsonProperty("mymusic")
  public List<Song> songs;
}
public class Song {
  @JsonProperty("Artist Name") public String artistName;
  @JsonProperty("Song Name") public String songName;
}

Library lib = mapper.readValue(jsonString, Library.class);

Google의 Gson을 확인해 주세요.http://code.google.com/p/google-gson/

웹 사이트:

Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

json 문자열의 모든 필드를 사용하여 MyType 클래스(물론 이름 변경)를 만들면 됩니다.어레이를 실행할 때 모든 파싱을 수동으로 수행하는 것이 더 복잡해질 수 있습니다(또한 매우 쉬운 경우). http://www.json.org/에서 Json 파서 개체의 Java 소스를 다운로드하십시오.

Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class); 

또한 Gson은 http://code.google.com/p/google-gson/에 적합합니다.

Gson은 Java 객체를 JSON 표현으로 변환하는 데 사용할 수 있는 Java 라이브러리입니다.또한 JSON 문자열을 동등한 Java 개체로 변환하는 데도 사용할 수 있습니다.Gson은 소스 코드가 없는 기존 개체를 포함하여 임의의 Java 개체를 사용할 수 있습니다."

Check the API examples: https://sites.google.com/site/gson/gson-user-guide#TOC-Overview More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

저 같은 경우에는 JSON 문자열을 리스트로 전달했습니다.따라서, 리스트를 건네줄 때는, 이하의 솔루션을 사용해 주십시오.

ObjectMapper mapper = new ObjectMapper();
String json = "[{\"classifier\":\"M\",\"results\":[{\"opened\":false}]}]";
List<Map<String, Object>>  map = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>(){});

underscore-java(개발자)는 json을 오브젝트로 변환할 수 있습니다.

import com.github.underscore.U;

    String jsonString = "{\n" +
            "        \"libraryname\":\"My Library\",\n" +
            "                \"mymusic\":[{\"Artist Name\":\"Aaron\",\"Song Name\":\"Beautiful\"},\n" +
            "        {\"Artist Name\":\"Britney\",\"Song Name\":\"Oops I did It Again\"},\n" +
            "        {\"Artist Name\":\"Britney\",\"Song Name\":\"Stronger\"}]}";
    Map<String, Object> jsonObject = U.fromJsonMap(jsonString);
    System.out.println(jsonObject);

    // {libraryname=My Library, mymusic=[{Artist Name=Aaron, Song Name=Beautiful}, {Artist Name=Britney, Song Name=Oops I did It Again}, {Artist Name=Britney, Song Name=Stronger}]}

    System.out.println(U.<String>get(jsonObject, "mymusic[0].Artist Name"));
    // Aaron
public void parseEmployeeObject() throws NoSuchFieldException, SecurityException, JsonParseException, JsonMappingException, IOException 
  {
   
      Gson gson = new Gson();
      
      ObjectMapper mapper = new ObjectMapper();

        // convert JSON string to Book object
        Object obj = mapper.readValue(Paths.get("src/main/resources/file.json").toFile(), Object.class);
        
        
        endpoint = this.endpointUrl;        

        String jsonInString = new Gson().toJson(obj);
    
      JsonRootPojo organisation = gson.fromJson(jsonInString, JsonRootPojo.class);
      
      
      for(JsonFilter jfil  : organisation.getSchedule().getTradeQuery().getFilter())
      {
         String name = jfil.getName();
         String value = jfil.getValue();
      }
      
      System.out.println(organisation);
      
  }

{
        "schedule": {
        "cron": "30 19 2 MON-FRI",
        "timezone": "Europe/London",        
        "tradeQuery": {
          "filter": [
            {
              "name": "bookType",
              "operand": "equals",
              "value": "FO"
            },
            {
              "name": "bookType",
              "operand": "equals",
              "value": "FO"
            }
          ],
          "parameter": [
            {
              "name": "format",
              "value": "CSV"
            },
            {
              "name": "pagesize",
              "value": "1000"
            }
          ]
        },
        "xslt" :""
        }
      
}


public class JesonSchedulePojo {
    
        public String cron;
        public String timezone;
        public JsonTradeQuery tradeQuery;
        public String xslt;
        
        
        public String getCron() {
            return cron;
        }
        public void setCron(String cron) {
            this.cron = cron;
        }
        public String getTimezone() {
            return timezone;
        }
        public void setTimezone(String timezone) {
            this.timezone = timezone;
        }
    
        public JsonTradeQuery getTradeQuery() {
            return tradeQuery;
        }
        public void setTradeQuery(JsonTradeQuery tradeQuery) {
            this.tradeQuery = tradeQuery;
        }
        public String getXslt() {
            return xslt;
        }
        public void setXslt(String xslt) {
            this.xslt = xslt;
        }
        @Override
        public String toString() {
            return "JesonSchedulePojo [cron=" + cron + ", timezone=" + timezone + ", tradeQuery=" + tradeQuery
                    + ", xslt=" + xslt + "]";
        }
        
        

public class JsonTradeQuery {
    
     public ArrayList<JsonFilter> filter;
        public ArrayList<JsonParameter> parameter;
        public ArrayList<JsonFilter> getFilter() {
            return filter;
        }
        public void setFilter(ArrayList<JsonFilter> filter) {
            this.filter = filter;
        }
        public ArrayList<JsonParameter> getParameter() {
            return parameter;
        }
        public void setParameter(ArrayList<JsonParameter> parameter) {
            this.parameter = parameter;
        }
        @Override
        public String toString() {
            return "JsonTradeQuery [filter=" + filter + ", parameter=" + parameter + "]";
        }
        
        
public class JsonFilter {

    public String name;
    public String operand;
    public String value;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getOperand() {
        return operand;
    }
    public void setOperand(String operand) {
        this.operand = operand;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return "JsonFilter [name=" + name + ", operand=" + operand + ", value=" + value + "]";
    }

public class JsonParameter {
    
    public String name;
    public String value;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return "JsonParameter [name=" + name + ", value=" + value + "]";
    }
    
    
public class JsonRootPojo {
    
    public JesonSchedulePojo schedule;

    public JesonSchedulePojo getSchedule() {
        return schedule;
    }

    

    public void setSchedule(JesonSchedulePojo schedule) {
        this.schedule = schedule;
    }



    @Override
    public String toString() {
        return "JsonRootPojo [schedule=" + schedule + "]";
    }

언급URL : https://stackoverflow.com/questions/10308452/how-to-convert-the-following-json-string-to-java-object

반응형