将大型JSON根据JAVA中的特定键值对拆分为多个小型JSON。

huangapple go评论64阅读模式
英文:

Break big JSON into separate small JSONs based on a specific key, value pair in JAVA

问题

以下是你想要的翻译内容:

String Team1 = "
{
  \"users\": [
    {
      \"displayName\": \"Dennis Law\",
      \"givenName\": \"Dennis\",
      \"surname\": \"Law\",
      \"extension_user_type\": \"user\",
      \"identities\": [
        {
          \"signInType\": \"emailAddress\",
          \"issuerAssignedId\": \"dennislaw@gmail.com\"
        }
      ],
      \"extension_timezone\": \"VET\",
      \"extension_locale\": \"en-IN\",
      \"extension_tenant\": \"Team1\"
    },
    {
      \"displayName\": \"Shaggy Nate\",
      \"givenName\": \"Shaggy\",
      \"surname\": \"Nate\",
      \"extension_user_type\": \"user\",
      \"identities\": [
        {
          \"signInType\": \"userName\",
          \"issuerAssignedId\": \"Shaggynatealpha\"
        }
      ],
      \"extension_timezone\": \"NST\",
      \"extension_locale\": \"en-AF\",
      \"extension_tenant\": \"Team1\"
    }
  ]
} ";

String Team2 = "
{
  \"users\": [
    {
      \"displayName\": \"Geroge West\",
      \"givenName\": \"Geroge\",
      \"surname\": \"West\",
      \"extension_user_type\": \"user\",
      \"identities\": [
        {
          \"signInType\": \"userName\",
          \"issuerAssignedId\": \"gwest\"
        }
      ],
      \"extension_timezone\": \"PST\",
      \"extension_locale\": \"en-GB\",
      \"extension_tenant\": \"Team2\"
    }
  ]
} ";
英文:

I have a JSON which I created from SQL Server using JSON PATH, below is how it looks, this JSON is stored in a STRING type of variable.

{
  "users": [
    {
      "displayName": "Dennis Law",
      "givenName": "Dennis",
      "surname": "Law",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "emailAddress",
          "issuerAssignedId": "dennislaw@gmail.com"
        }
      ],
      "extension_timezone": "VET",
      "extension_locale": "en-IN",
      "extension_tenant": "Team1"
    },
    {
      "displayName": "Geroge West",
      "givenName": "Geroge",
      "surname": "West",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "userName",
          "issuerAssignedId": "gwest"
        }
      ],
      "extension_timezone": "PST",
      "extension_locale": "en-GB",
      "extension_tenant": "Team2"
    },
    {
      "displayName": "Shaggy Nate",
      "givenName": "Shaggy",
      "surname": "Nate",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "userName",
          "issuerAssignedId": "Shaggynatealpha"
        }
      ],
      "extension_timezone": "NST",
      "extension_locale": "en-AF",
      "extension_tenant": "Team1"
    }
  ]
}

In the below JSON, I have a key extension_tenant which is like a team, so we have values like Team1, Team2, Team3...and so on

I want to know if there is a way I can break this JSON based on extension_tenant and store it in STRING based on extension_tenant, so it will look like this.

Suppose all with extension_tenant = Team1 will be stored in a separate STRING,

example :

String Team1 = "

{
  "users": [
    {
      "displayName": "Dennis Law",
      "givenName": "Dennis",
      "surname": "Law",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "emailAddress",
          "issuerAssignedId": "dennislaw@gmail.com"
        }
      ],
      "extension_timezone": "VET",
      "extension_locale": "en-IN",
      "extension_tenant": "Team1"
    },
    {
      "displayName": "Shaggy Nate",
      "givenName": "Shaggy",
      "surname": "Nate",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "userName",
          "issuerAssignedId": "Shaggynatealpha"
        }
      ],
      "extension_timezone": "NST",
      "extension_locale": "en-AF",
      "extension_tenant": "Team1"
    }
  ]
} ";

and for all with extension_tenant as Team2

String Team2 = "
{
  "users": [
    {
      "displayName": "Geroge West",
      "givenName": "Geroge",
      "surname": "West",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "userName",
          "issuerAssignedId": "gwest"
        }
      ],
      "extension_timezone": "PST",
      "extension_locale": "en-GB",
      "extension_tenant": "Team2"
    }
  ]
} ";

I hope I was able to explain what I am trying to do, please suggest and approach, I am active on stackoverflow, so i will probably reply and work on suggestions immediately. I am also looking for ways to do it mean while.

答案1

得分: 1

以下是您提供的代码的翻译:

检查以下方法是否适用于您

User.java

package json;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    @JsonProperty("displayName")
    private String displayName;

    @JsonProperty("givenName")
    private String givenName;

    @JsonProperty("surname")
    private String surname;

    @JsonProperty("extension_user_type")
    private String extension_user_type;

    @JsonProperty("identities")
    private List<Identity> identities;

    @JsonProperty("extension_timezone")
    private String extension_timezone;

    @JsonProperty("extension_locale")
    private String extension_locale;

    @JsonProperty("extension_tenant")
    private String extension_tenant;

    /**
     * @return the displayName
     */
    public String getDisplayName() {
        return displayName;
    }

    // ... (其他getter和setter方法)

    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append('{');
        stringBuilder.append("\"displayName\":\"" + displayName + "\",");
        stringBuilder.append("\"givenName\":\"" + givenName + "\",");
        stringBuilder.append("\"surname\":\"" + surname + "\",");
        stringBuilder.append("\"extension_user_type\":\"" + extension_user_type + "\",");
        // ... (其他属性拼接)
        stringBuilder.append('}');
        return stringBuilder.toString();
    }
}

Identity.java

package json;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Identity {
    @JsonProperty("signInType")
    private String signInType;

    @JsonProperty("issuerAssignedId")
    private String issuerAssignedId;

    // ... (getter和setter方法)

    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append('{');
        stringBuilder.append("\"signInType\":\"" + signInType + "\",");
        stringBuilder.append("\"issuerAssignedId\":\"" + issuerAssignedId + "\"");
        stringBuilder.append('}');
        return stringBuilder.toString();
    }
}

Users.java

package json;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Users {
    @JsonProperty("users")
    List<User> users;

    // ... (getter和setter方法)

    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append('{');

        if (users != null && users.size() > 0) {
            stringBuilder.append("\"users\":[");
            for (User user : users) {
                stringBuilder.append(user);
            }
            stringBuilder.append("]");
        }
        stringBuilder.append('}');
        return stringBuilder.toString();
    }
}

将JSON存储到d:/test.json中

在反序列化后在extension_tenant属性上进行分组

Converter.java

package json;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Converter {
    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        InputStream inputStream = null;
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                false);
        Users users = null;
        try {
            inputStream = new FileInputStream("d:/testsep.json");
            // 获取Users对象
            users = mapper.readValue(inputStream, Users.class);
            StringBuilder stringBuilder = new StringBuilder();
            Map<String, String> groupByTenantmap = null;
            if (users != null) {
                // 检索User对象列表
                List<User> userList = users.getUsers();
                if (userList != null && userList.size() > 0) {
                    groupByTenantmap = new HashMap<String, String>(
                            userList.size());
                    String extension_tenant = null;
                    String value = null;
                    for (User user : userList) {
                        // 按extension_tenant进行分组
                        extension_tenant = user.getExtension_tenant();
                        if (groupByTenantmap.containsKey(extension_tenant)) {
                            value = groupByTenantmap.get(extension_tenant);
                            stringBuilder.append(value).append(',').append(user.toString());
                            groupByTenantmap.put(extension_tenant, stringBuilder.toString());
                        } else {
                            groupByTenantmap.put(extension_tenant, user.toString());
                        }
                        stringBuilder.setLength(0);
                    }
                    
                    // 遍历映射并创建所需的JSON结构
                    for (Entry<String, String> entry : groupByTenantmap.entrySet()) {
                        stringBuilder.setLength(0);
                        stringBuilder.append("{").append("\"users\":").append("[");
                        stringBuilder.append(entry.getValue()).append("]");
                        stringBuilder.append("}");
                        System.out.println("String " + entry.getKey() + "=\"" + stringBuilder.toString() + "\";");
                        System.out.println();
                    }
                }
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

输出:

String Team2="{"users":[{"displayName":"Geroge West","givenName":"Geroge","surname":"West","extension_user_type":"user","identities": [{"signInType":"userName","issuerAssignedId":"gwest"}],"extension_timezone":"PST","extension_locale":"en-GB","extension_tenant":"Team2"}]}";

String Team1="{"users":[{"displayName":"Dennis Law","givenName":"Dennis","surname":"Law","extension_user_type":"user","identities": [{"signInType":"emailAddress","issuerAssignedId":"dennislaw@gmail.com"}],"extension_timezone":"VET","extension_locale":"en-IN","extension_tenant":"Team1"},{"displayName":"Shaggy Nate","givenName":"Shaggy","surname":"Nate","extension_user_type":"user","identities": [{"signInType":"userName","issuerAssignedId":"Shaggynatealpha"}],"extension_timezone":"NST","extension_locale":"en-AF","extension_tenant":"Team1"}]}";

请注意,这是您提供的代码的直接翻译,代码中的注释和特定于变量命名的内容也得以保留。如果您需要进一步的解释或修改,请随时提问。

英文:

Check if following approach work for you

User.java

package json;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
@JsonProperty(&quot;displayName&quot;)
private String displayName;
@JsonProperty(&quot;givenName&quot;)
private String givenName;
@JsonProperty(&quot;surname&quot;)
private String surname;
@JsonProperty(&quot;extension_user_type&quot;)
private String extension_user_type;
@JsonProperty(&quot;identities&quot;)
private List&lt;Identity&gt; identities;
@JsonProperty(&quot;extension_timezone&quot;)
private String extension_timezone;
@JsonProperty(&quot;extension_locale&quot;)
private String extension_locale;
@JsonProperty(&quot;extension_tenant&quot;)
private String extension_tenant;
/**
* @return the displayName
*/
public String getDisplayName() {
return displayName;
}
/**
* @param displayName
*            the displayName to set
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* @return the givenName
*/
public String getGivenName() {
return givenName;
}
/**
* @param givenName
*            the givenName to set
*/
public void setGivenName(String givenName) {
this.givenName = givenName;
}
/**
* @return the surname
*/
public String getSurname() {
return surname;
}
/**
* @param surname
*            the surname to set
*/
public void setSurname(String surname) {
this.surname = surname;
}
/**
* @return the extension_user_type
*/
public String getExtension_user_type() {
return extension_user_type;
}
/**
* @param extension_user_type
*            the extension_user_type to set
*/
public void setExtension_user_type(String extension_user_type) {
this.extension_user_type = extension_user_type;
}
/**
* @return the identities
*/
public List&lt;Identity&gt; getIdentities() {
return identities;
}
/**
* @param identities
*            the identities to set
*/
public void setIdentities(List&lt;Identity&gt; identities) {
this.identities = identities;
}
/**
* @return the extension_timezone
*/
public String getExtension_timezone() {
return extension_timezone;
}
/**
* @param extension_timezone
*            the extension_timezone to set
*/
public void setExtension_timezone(String extension_timezone) {
this.extension_timezone = extension_timezone;
}
/**
* @return the extension_locale
*/
public String getExtension_locale() {
return extension_locale;
}
/**
* @param extension_locale
*            the extension_locale to set
*/
public void setExtension_locale(String extension_locale) {
this.extension_locale = extension_locale;
}
/**
* @return the extension_tenant
*/
public String getExtension_tenant() {
return extension_tenant;
}
/**
* @param extension_tenant
*            the extension_tenant to set
*/
public void setExtension_tenant(String extension_tenant) {
this.extension_tenant = extension_tenant;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(&#39;{&#39;);
stringBuilder.append(&quot;\&quot;displayName\&quot;:&quot; + &quot;\&quot;&quot; + displayName + &quot;\&quot;,&quot;);
stringBuilder.append(&quot;\&quot;givenName\&quot;:&quot; + &quot;\&quot;&quot; + givenName + &quot;\&quot;,&quot;);
stringBuilder.append(&quot;\&quot;surname\&quot;:&quot; + &quot;\&quot;&quot; + surname + &quot;\&quot;,&quot;);
stringBuilder.append(&quot;\&quot;extension_user_type\&quot;:&quot; + &quot;\&quot;&quot;
+ extension_user_type + &quot;\&quot;,&quot;);
if (identities != null &amp;&amp; identities.size() &gt; 0) {
stringBuilder.append(&quot;\&quot;identities\&quot;: [&quot;);
for (Identity identity : identities) {
stringBuilder.append(identity);
}
stringBuilder.append(&quot;],&quot;);
}
stringBuilder.append(&quot;\&quot;extension_timezone\&quot;:&quot; + &quot;\&quot;&quot;
+ extension_timezone + &quot;\&quot;,&quot;);
stringBuilder.append(&quot;\&quot;extension_locale\&quot;:&quot; + &quot;\&quot;&quot; + extension_locale
+ &quot;\&quot;,&quot;);
stringBuilder.append(&quot;\&quot;extension_tenant\&quot;:&quot; + &quot;\&quot;&quot; + extension_tenant
+ &quot;\&quot;&quot;);
stringBuilder.append(&#39;}&#39;);
return stringBuilder.toString();
}
}

Identity.java

package json;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Identity {
@JsonProperty(&quot;signInType&quot;)
private String signInType;
@JsonProperty(&quot;issuerAssignedId&quot;)
private String issuerAssignedId;
/**
* @return the signInType
*/
public String getSignInType() {
return signInType;
}
/**
* @param signInType
*            the signInType to set
*/
public void setSignInType(String signInType) {
this.signInType = signInType;
}
/**
* @return the issuerAssignedId
*/
public String getIssuerAssignedId() {
return issuerAssignedId;
}
/**
* @param issuerAssignedId
*            the issuerAssignedId to set
*/
public void setIssuerAssignedId(String issuerAssignedId) {
this.issuerAssignedId = issuerAssignedId;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(&#39;{&#39;);
stringBuilder.append(&quot;\&quot;signInType\&quot;:&quot; + &quot;\&quot;&quot; + signInType + &quot;\&quot;,&quot;);
stringBuilder.append(&quot;\&quot;issuerAssignedId\&quot;:&quot; + &quot;\&quot;&quot; + issuerAssignedId
+ &quot;\&quot;&quot;);
stringBuilder.append(&#39;}&#39;);
return stringBuilder.toString();
}
}

Users.java

package json;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Users {
@JsonProperty(&quot;users&quot;)
List&lt;User&gt; users;
/**
* @return the users
*/
public List&lt;User&gt; getUsers() {
return users;
}
/**
* @param users
*            the users to set
*/
public void setUsers(List&lt;User&gt; users) {
this.users = users;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(&#39;{&#39;);
if (users != null &amp;&amp; users.size() &gt; 0) {
stringBuilder.append(&quot;\&quot;users\&quot;: [&quot;);
for (User user : users) {
stringBuilder.append(user);
}
stringBuilder.append(&quot;]&quot;);
}
stringBuilder.append(&#39;}&#39;);
return stringBuilder.toString();
}
}

Stored the json into d:/test.json

Post deserialization doing group by on extension_tenant attribute.

Converter.java

package json;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Converter {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = null;
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
Users users = null;
try {
inputStream = new FileInputStream(&quot;d:/testsep.json&quot;);
//Get Users object
users = mapper.readValue(inputStream, Users.class);
StringBuilder stringBuilder = new StringBuilder();
Map&lt;String, String&gt; groupByTenantmap = null;
if (users != null) {
//retrieve list of User object
List&lt;User&gt; userList = users.getUsers();
if (userList != null &amp;&amp; userList.size() &gt; 0) {
groupByTenantmap = new HashMap&lt;String, String&gt;(
userList.size());
String extension_tenant = null;
String value = null;
for (User user : userList) {
//populate map group by extension_tenant
extension_tenant = user.getExtension_tenant();
if (groupByTenantmap.containsKey(extension_tenant)) {
value = groupByTenantmap.get(extension_tenant);
stringBuilder.append(value).append(&#39;,&#39;)
.append(user.toString());
groupByTenantmap.put(extension_tenant,
stringBuilder.toString());
} else {
groupByTenantmap.put(extension_tenant,
user.toString());
}
stringBuilder.setLength(0);
}
//iterate through map and create desired json structure
for (Entry&lt;String, String&gt; entry : groupByTenantmap
.entrySet()) {
stringBuilder.setLength(0);
stringBuilder.append(&quot;{&quot;).append(&quot;\&quot;users\&quot;:&quot;)
.append(&quot;[&quot;);
stringBuilder.append(entry.getValue()).append(&quot;]&quot;);
stringBuilder.append(&quot;}&quot;);
System.out.println(&quot;String &quot; + entry.getKey() + &quot;=\&quot;&quot;
+ stringBuilder.toString() + &quot;\&quot;;&quot;);
System.out.println();
}
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Output:

String Team2=&quot;{&quot;users&quot;:[{&quot;displayName&quot;:&quot;Geroge West&quot;,&quot;givenName&quot;:&quot;Geroge&quot;,&quot;surname&quot;:&quot;West&quot;,&quot;extension_user_type&quot;:&quot;user&quot;,&quot;identities&quot;: [{&quot;signInType&quot;:&quot;userName&quot;,&quot;issuerAssignedId&quot;:&quot;gwest&quot;}],&quot;extension_timezone&quot;:&quot;PST&quot;,&quot;extension_locale&quot;:&quot;en-GB&quot;,&quot;extension_tenant&quot;:&quot;Team2&quot;}]}&quot;;
String Team1=&quot;{&quot;users&quot;:[{&quot;displayName&quot;:&quot;Dennis Law&quot;,&quot;givenName&quot;:&quot;Dennis&quot;,&quot;surname&quot;:&quot;Law&quot;,&quot;extension_user_type&quot;:&quot;user&quot;,&quot;identities&quot;: [{&quot;signInType&quot;:&quot;emailAddress&quot;,&quot;issuerAssignedId&quot;:&quot;dennislaw@gmail.com&quot;}],&quot;extension_timezone&quot;:&quot;VET&quot;,&quot;extension_locale&quot;:&quot;en-IN&quot;,&quot;extension_tenant&quot;:&quot;Team1&quot;},{&quot;displayName&quot;:&quot;Shaggy Nate&quot;,&quot;givenName&quot;:&quot;Shaggy&quot;,&quot;surname&quot;:&quot;Nate&quot;,&quot;extension_user_type&quot;:&quot;user&quot;,&quot;identities&quot;: [{&quot;signInType&quot;:&quot;userName&quot;,&quot;issuerAssignedId&quot;:&quot;Shaggynatealpha&quot;}],&quot;extension_timezone&quot;:&quot;NST&quot;,&quot;extension_locale&quot;:&quot;en-AF&quot;,&quot;extension_tenant&quot;:&quot;Team1&quot;}]}&quot;;

huangapple
  • 本文由 发表于 2020年9月30日 23:08:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64140526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定